<template>
  <div class="page-main" v-title data-title="项目变更页面">
    <a-spin :spinning="btnLoading" tip="保存中...">
      <div class="container" ref="imageWrapper" :loading="btnLoading">
        <div class="head-content">
          <span class="bold-font">工程项目变更审批表</span>
          <ul>
            <li @click="openChangeRecordLog"><span class="iconfont icon-faqi"></span>变更日志</li>
            <li @click="openChangeRecordHistory"><span class="iconfont icon-faqi"></span>变更历史</li>
            <li @click="openChangeRecordTips"><span class="iconfont icon-faqi"></span>审批流程说明</li>
            <li @click="openChangeRecordGuide"><span class="iconfont icon-faqi"></span>操作指引</li>
            <li @click="toPrint"><span class="iconfont icon-faqi"></span>打印</li>
          </ul>
          <div class="btn-line">
            <a-button
              @click="save(false)"
              :loading="btnLoading"
              v-if="!projectChangeData.status || [0, 1, 4].indexOf(projectChangeData.status) > -1"
              >保存</a-button
            >
            <a-button
              type="primary"
              @click="onSubmit"
              :loading="btnLoading"
              v-if="btnShow && [1, 0, 4].indexOf(projectChangeData.status) > -1"
              >提交审批
            </a-button>
            <a-button
              @click="del"
              :loading="btnLoading"
              style="color: red"
              v-if="
                projectChangeData.status &&
                projectChangeData.status === 1 &&
                (projectChangeData.createUserId === currentUserId || projectBuildData.projectSubTypeAdmin)
              "
              >删除</a-button
            >
            <!-- <a-button style="margin-right: 20px" @click="projectReserve" v-if="reserveBtnShow">
            <a-icon type="select" />转储备
          </a-button> -->
          </div>
        </div>
        <div class="app-container">
          <a-form-model
            ref="ruleForm"
            :model="projectChangeData"
            :rules="rules"
            style="margin-top: 10px"
            label-width="160px"
            label-position="right"
          >
            <section>
              <div class="section-header">
                <div>基本信息</div>
                <div style="font-size: 14px; font-weight: normal">
                  <span v-if="buildCompanyLeader" style="color: red">工程委参与该项目立项审批过程</span
                  ><a-button type="link" @click="toProjectDetail">项目详情</a-button>
                </div>
              </div>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="变更单号:">
                    <a-input
                      id="projectChangeNo"
                      v-model="projectChangeData.projectChangeNo"
                      placeholder="自动生成"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请人/部门:">
                    <a-input :value="getApplyUserAndDept()" placeholder="自动生成" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请时间:">
                    <a-input
                      :value="
                        projectChangeData.submitTime ? projectChangeData.submitTime : projectChangeData.createTime
                      "
                      placeholder="自动生成"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="项目编号:" prop="projectNo">
                    <a-input-search
                      placeholder="项目编号"
                      :readOnly="projectChangeData.isHteProject == '1'"
                      v-model="projectChangeData.projectNo"
                      :disabled="projectChangeData.id > 0 || addByProject == 'true'"
                      @search="openProjectSelector"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="项目名称">
                    <a-input
                      v-model="projectChangeData.projectName"
                      placeholder="项目名称"
                      prop="projectName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="项目经理:" prop="projectManager">
                    <UserInputSelector
                      :username.sync="projectChangeData.projectManagerId"
                      :realname.sync="projectChangeData.projectManager"
                      disabled
                      multiple="multiple"
                      placeholder="请选择人员"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="16">
                  <a-form-model-item label="项目变更名称:" prop="projectChangeName">
                    <a-input
                      v-model="projectChangeData.projectChangeName"
                      placeholder="简明表达变更主题"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="变更类型:" prop="changeType">
                    <a-select
                      v-model="projectChangeData.changeType"
                      placeholder="请选择变更类型"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    >
                      <a-select-option
                        v-for="(item, index) in codes['工程项目变更类型']"
                        :key="'changeType_' + index"
                        :value="item.name"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="变更责任部门:" prop="dutyDeptName">
                    <a-input disabled  v-model="projectChangeData.dutyDeptName" placeholder="选择变更负责人后自动填充"></a-input>
                    <!-- <a-input-search
                      placeholder="填写一个主要责任部门"
                      v-model="projectChangeData.dutyDeptName"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                      @search="openDeptSelector('dutyDeptName')"
                    >
                      <a-button slot="enterButton"> ... </a-button>
                    </a-input-search> -->
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="变更负责人:" prop="dutyUserName">
                    <UserInputSelector
                      :username.sync="projectChangeData.dutyUserId"
                      :realname.sync="projectChangeData.dutyUserName"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                      multiple="multiple"
                      placeholder="可多选"
                      selectedReturn="1"
                      @selected="value=>selectdutyUser(value)"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item label="项目预算变更:" prop="budgetChangeContentList">
                    <a-checkbox-group
                      v-model="budgetChangeContentList"
                      :disabled="(projectChangeData.status && projectChangeData.status != '1') || !projectBuildData.id"
                      @change="changeBudgetChangeContentList"
                    >
                      <a-checkbox
                        v-for="(item, index) in codes['工程项目项目预算变更类型']"
                        :key="'changeType_' + index"
                        :value="item.code"
                        >{{ item.name }}</a-checkbox
                      >
                    </a-checkbox-group>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item label="项目基本变更:" :labelCol="{ span: 15 }" prop="changeContentList">
                    <a-checkbox-group
                      v-model="changeContentList"
                      @change="changeContentChange"
                      :disabled="(projectChangeData.status && projectChangeData.status != '1') || !projectBuildData.id"
                    >
                      <a-checkbox
                        v-for="(item, index) in codes['工程项目其他变更内容']"
                        v-show="item.parentid == '1'"
                        :key="'changeContentList_' + index"
                        :value="item.code"
                        >{{ item.name }}</a-checkbox
                      >
                    </a-checkbox-group>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item label="项目合同变更:">
                    <a-checkbox-group
                      v-model="contractChangeContentArr"
                      @change="changeContractChangeContent"
                      :disabled="
                        (projectChangeData.status && projectChangeData.status != '1') || !projectChangeData.projectNo
                      "
                    >
                      <a-checkbox
                        v-for="(item, index) in codes['工程项目变更合同涉及内容']"
                        v-show="item.parentid == '1'"
                        :key="'contractChangeContent_' + index"
                        :value="item.code"
                        >{{ item.name }}</a-checkbox
                      >
                    </a-checkbox-group>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item label="变更原因说明:" prop="changeReason">
                    <a-textarea
                      v-model="projectChangeData.changeReason"
                      placeholder="请输入变更原因"
                      :auto-size="{ minRows: 3, maxRows: 10 }"
                      style="margin-top: 5px"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item label="变更影响分析:" prop="changeInfluence">
                    <a-textarea
                      v-model="projectChangeData.changeInfluence"
                      placeholder="请输入变更后对项目的影响"
                      :auto-size="{ minRows: 3, maxRows: 10 }"
                      style="margin-top: 5px"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row v-show="projectBuildData.projectClass === '40' && projectChangeData.changeType === '土建'">
                <a-col :span="24">
                  <!-- <a-icon type="transaction" style="margin-right: 5px" id="costAuditRemark" /><span
                style="font-weight: bolder"
                >造价员审核结论</span
              > -->

                  <a-form-model-item
                    label="造价员审核结论"
                    :prop="
                      currentNodeDefKey !== 'costDepartment' && currentNodeDefKey !== 'costDepartmentSupervisor'
                        ? ''
                        : 'costAuditRemark'
                    "
                  >
                    <div style="display: flex; align-items: center">
                      <span style="white-space: nowrap; color: red">*</span>
                      <span style="white-space: nowrap"> 此次变更费用审核为： </span>
                      <a-input
                        v-model="projectChangeData.auditChangeTotal"
                        placeholder="请输入此次变更费用"
                        style="border-color: red; width: 130px; text-align: right; margin: 5 2px"
                        :disabled="
                          currentNodeDefKey !== 'costDepartment' && currentNodeDefKey !== 'costDepartmentSupervisor'
                        "
                      />
                      <span style="white-space: nowrap"> 元。 </span>
                      <span style="white-space: nowrap; color: red; margin-left: 5px">*</span>
                      <span style="white-space: nowrap"> 若追加至SAP系统不含税金额为： </span>
                      <a-input
                        v-model="projectChangeData.auditAddToSapTotal"
                        placeholder="追加至SAP系统不含税金额"
                        style="border-color: red; width: 130px; text-align: right; margin: 5 2px"
                        :disabled="
                          currentNodeDefKey !== 'costDepartment' && currentNodeDefKey !== 'costDepartmentSupervisor'
                        "
                      />
                      <span style="white-space: nowrap"> 元。其他说明： </span>
                      <a-textarea
                        v-model="projectChangeData.costAuditRemark"
                        placeholder="其他说明"
                        auto-size
                        style="border-color: red; margin: 5 2px"
                        :disabled="
                          currentNodeDefKey !== 'costDepartment' && currentNodeDefKey !== 'costDepartmentSupervisor'
                        "
                      />
                    </div>
                    <div style="color: #ff0000; line-height: 18px">
                      <div style="line-height: 18px">注：如不涉及造价审核，费用均填0，并说明无需造价审核</div>
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="24" class="tipsLabel">
                  <a-form-model-item
                    label="变更选项说明:"
                    :labelCol="{ span: 15, style: { color: '#FF0000' } }"
                    labelStyle=""
                  >
                    <div style="color: #ff0000; line-height: 18px">
                      <div style="line-height: 18px">
                        若发起项目变更流程，项目预算变更、项目合同变更、项目基本变更，至少勾选其中一项才可发起项目变更审批流程，否者无法提交审批。
                      </div>
                      <div>
                        【项目总预算调整】需追加或追减SAP项目预算总额；【项目内预算调整】是仅调整项目内WBS预算子项金额，不调整项目预算总额；【费用支出公司调整】是项目投资方变更。
                      </div>
                      <div>
                        【项目合同变更】是属于本项目内的合同进行费用调整或者进度调整。【项目销项】是审批本项目不再执行，变更审批通过后需继续走项目关闭审批流
                        程，对项目进行合同订单、物资清算、然后在SAP中关闭。
                      </div>
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </section>
            <section
              v-if="
                budgetChangeContentList &&
                budgetChangeContentList.length > 0 &&
                (budgetChangeContentList.indexOf('1') > -1 ||
                  budgetChangeContentList.indexOf('2') > -1 ||
                  budgetChangeContentList.indexOf('3') > -1)
              "
            >
              <div class="section-header">项目预算变更信息</div>
              <a-row>
                <div style="display: flex; align-items: center; line-height: 60px">
                  <a-icon type="menu-unfold" style="margin-right: 5px" /><span style="font-weight: bolder"
                    >变更说明</span
                  >
                  <div>
                    本次变更费用为不含税￥
                    <a-input
                      placeholder="必填，输入数字"
                      style="border-color: red; width: 130px; text-align: right; margin: 0 2px"
                      v-model="projectChangeData.changeTotal"
                      @blur="checkInputMoney"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    />元， 需追加至SAP系统费用不含税￥
                    <a-input
                      placeholder="必填，输入数字"
                      style="border-color: red; width: 130px; text-align: right; margin: 0 2px"
                      v-model="projectChangeData.addToSapTotal"
                      @blur="checkInputMoney"
                      :disabled="
                        (projectChangeData.status && projectChangeData.status != '1') ||
                        budgetChangeContentList.indexOf('2') > -1
                      "
                    />元
                  </div>
                </div>
              </a-row>
              <a-row v-if="budgetChangeContentList && budgetChangeContentList.length > 0">
                <a-icon type="menu-unfold" style="margin-right: 1px" /><span style="font-weight: bolder"
                  >预算项变更</span
                >
                <span style="color: red">（单位：元(不含税)）</span>
                <a-button
                  type="primary"
                  style="width: 80px; margin-right: 15px; margin-left: 15px"
                  @click="addFactory"
                  v-if="btnShow"
                  >添加</a-button
                >
                <a-button style="width: 80px; margin-right: 15px" @click="delBudgetItem" v-if="btnShow">删除</a-button>
                <a-button style="margin-right: 15px" @click="changeCostCenter" v-if="btnShow">修改成本中心号</a-button>
                <span>
                  <a-icon type="exclamation-circle" theme="filled" style="color: #47a4fa" />
                  注意：各分项费用之和需等于追加SAP系统费用，费用减少则填写负值。
                </span>
                <!--<a-table
                v-if="budgetGroups && budgetGroups.length > 0"
                :scroll="{ x: true }"
                :columns="budgetGroupColumns"
                :data-source="budgetGroups"
                bordered
                rowKey="factoryCode"
                :defaultExpandAllRows="false"
                :pagination="false"
                style="margin-top: 5px; margin-bottom: 5px"
                :row-selection="{ selectedRowKeys: selectedBudgetItemRowKeys, onChange: onSelectBudgetItemChange }"
              >
                <a-table
                  class="inner-table"
                  :scroll="{ x: true }"
                  slot="expandedRowRender"
                  slot-scope="group"
                  :columns="budgetListColumns"
                  :data-source="group.budgetList"
                  rowKey="projectBudgetCode"
                  :pagination="false"
                >
                  <template slot="changeAmount" slot-scope="text, record">
                    <a-input
                      placeholder="请输入数字"
                      v-model="record.changeAmount"
                      @blur="(event) => changeAmountChange(event, record)"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    />
                  </template>
                  <template slot="originAmount" slot-scope="text">
                    <span>{{ parseFloat(text).toLocaleString() }}</span>
                  </template>
                  <template slot="historyChangeAmount" slot-scope="text">
                    <span>{{ parseFloat(text).toLocaleString() }}</span>
                  </template>
                  <template slot="memo" slot-scope="text, record">
                    <a-textarea
                      placeholder="请输入说明内容"
                      auto-size
                      v-model="record.memo"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    />
                  </template>
                </a-table>
                <template slot="factoryName" slot-scope="text, record">
                  <a-input-search
                    placeholder="付款公司"
                    readOnly
                    :value="
                      record.factoryName && record.factoryCode ? record.factoryName + '/' + record.factoryCode : ''
                    "
                   :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    @search="openFactorySelector(record)"
                  />
                </template>
                <template slot="factory" slot-scope="text, record">
                  <span>{{ record.factoryCode + '(' + record.factory + ')' }}</span>
                </template>
                <template slot="costCenterNo" slot-scope="text, record">
                  <a-textarea
                    placeholder="请输入成本中心号"
                    auto-size
                    v-model="record.costCenterNo"
                   :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                  />
                </template>
              </a-table>-->
                <ExpandedRowsTable
                  style="margin-top: 5px; margin-bottom: 5px"
                  ref="expandTreeTable"
                  :data="budgetItemTree"
                  :loading="tabLoading"
                  :columns="changeCols"
                  :rowKey="rowKey"
                  :editTable="!(projectChangeData.status && projectChangeData.status != '1')"
                  :rowSelection="rowSelection"
                  @changeAmountChange="changeAmountChange"
                >
                </ExpandedRowsTable>
                <ul class="totalExpenses">
                  <li>
                    原来预算总费用（元）：
                    <span>￥</span><span>{{ totalAmount }}</span
                    ><span>（￥</span>{{ totalTenThousand }}<span style="margin-right: 20px">万）</span>
                    <span style="color: red">
                      本次变更总费用（元）：
                      <span>￥</span><span>{{ totalAmountChange }}</span
                      ><span>（￥</span>{{ totalTenThousandChange }}<span style="margin-right: 20px">万）</span>
                    </span>
                    历史变更总费用（元）：
                    <span>￥</span><span>{{ amountHistory }}</span
                    ><span>（￥</span>{{ amountHistoryTenThousand }}<span>万）</span>
                    <span style="color: red">
                      变更费用百分比：
                      <span>{{ changePercent + '%' }}</span>
                    </span>
                  </li>
                </ul>
              </a-row>
            </section>
            <section
              v-if="
                contractChangeContentArr &&
                (contractChangeContentArr.indexOf('91') > -1 || contractChangeContentArr.indexOf('92') > -1)
              "
            >
              <div class="section-header">项目合同变更信息</div>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="变更合同编号:" prop="contractNumber">
                    <a-input-search
                      readOnly
                      placeholder="选择关联合同编号"
                      v-model="projectChangeData.contractNumber"
                      @search="openWorkReportProjectSelector"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="变更合同名称:" prop="contractName">
                    <a-input disabled placeholder="变更合同名称" v-model="projectChangeData.contractName" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="费用支出号:">
                    <a-input disabled placeholder="费用支出号" v-model="projectChangeData.contractCostNumber" />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" v-if="contractChangeContentArr.indexOf('91') > -1">
                <a-col :span="8">
                  <div style="display: flex" class="multipleForm">
                    <div style="width: 70%">
                      <a-form-model-item
                        label="费用变更类型:"
                        :prop="contractChangeContentArr.indexOf('91') > -1 ? 'contractCostChangeType' : ''"
                        :labelCol="{ style: 'width: 160px' }"
                      >
                        <a-select
                          v-model="projectChangeData.contractCostChangeType"
                          allowClear
                         :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                        >
                          <a-select-option
                            v-for="(code, index) in codes['工程项目变更合同费用变更类型']"
                            :key="index"
                            :value="code.code"
                          >
                            {{ code.name }}
                          </a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </div>
                    <div style="width: 30%">
                      <a-form-model-item
                        :labelCol="{ style: 'width: 0px' }"
                        :prop="contractChangeContentArr.indexOf('91') > -1 ? 'contractChangeAmount' : ''"
                      >
                        <a-input
                          placeholder="合同变更金额"
                          v-model="projectChangeData.contractChangeAmount"
                          suffix="元"
                         :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                        />
                      </a-form-model-item>
                    </div>
                  </div>
                </a-col>
                <a-col :span="16">
                  <a-form-model-item
                    label="费用变更原因:"
                    :prop="contractChangeContentArr.indexOf('91') > -1 ? 'contractCostChangeReason' : ''"
                  >
                    <a-select
                      mode="multiple"
                      v-model="contractCostChangeReasonArr"
                      style="width: 100%"
                      allowClear
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    >
                      <a-select-option
                        v-for="(code, index) in codes['工程项目变更合同费用变更原因']"
                        :key="index"
                        :value="code.code"
                      >
                        {{ code.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" v-if="contractChangeContentArr.indexOf('92') > -1">
                <a-col :span="8">
                  <div style="display: flex" class="multipleForm">
                    <div style="width: 70%">
                      <a-form-model-item
                        label="进度变更类型:"
                        :prop="contractChangeContentArr.indexOf('92') > -1 ? 'contractTimeChangeType' : ''"
                        :labelCol="{ style: 'width: 160px' }"
                      >
                        <a-select
                          v-model="projectChangeData.contractTimeChangeType"
                          allowClear
                         :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                        >
                          <a-select-option
                            v-for="(code, index) in codes['工程项目变更合同进度变更类型']"
                            :key="index"
                            :value="code.code"
                          >
                            {{ code.name }}
                          </a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </div>
                    <div style="width: 30%">
                      <a-form-model-item
                        :prop="contractChangeContentArr.indexOf('92') > -1 ? 'contractTimeChangeDays' : ''"
                        :labelCol="{ style: 'width: 0px' }"
                      >
                        <a-input
                          placeholder="影响天数"
                          v-model="projectChangeData.contractTimeChangeDays"
                          suffix="天"
                         :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                        />
                      </a-form-model-item>
                    </div>
                  </div>
                </a-col>
                <a-col :span="16">
                  <a-form-model-item
                    label="进度变更原因:"
                    :prop="contractChangeContentArr.indexOf('92') > -1 ? 'contractTimeChangeReason' : ''"
                  >
                    <a-select
                      mode="multiple"
                      v-model="contractTimeChangeReasonArr"
                      allowClear
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    >
                      <a-select-option
                        v-for="(code, index) in codes['工程项目变更合同进度变更原因']"
                        :key="index"
                        :value="code.code"
                      >
                        {{ code.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </section>
            <section v-if="projectChangeData.status === 3">
              <div class="section-header">预算下达情况</div>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item
                    label="下达状态"
                    prop="budgetStatus"
                    :labelCol="{ span: 3 }"
                    :wrapperCol="{ span: 21 }"
                  >
                    <span
                      :style="{
                        color:
                          projectChangeData.budgetStatus === 2
                            ? 'green'
                            : projectChangeData.budgetStatus === 1
                            ? 'orange'
                            : 'red',
                      }"
                    >
                      {{
                        projectChangeData.budgetStatus === 2
                          ? '已下达'
                          : projectChangeData.budgetStatus === 1
                          ? '已调整WBS'
                          : '未下达'
                      }}
                    </span>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item
                    label="调整WBS备注"
                    prop="wbsMemo"
                    :labelCol="{ span: 3 }"
                    :wrapperCol="{ span: 21 }"
                  >
                    <a-textarea
                      v-model="projectChangeData.wbsMemo"
                      auto-size
                      style="margin-top: 5px"
                      readOnly
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item
                    label="下达预算备注"
                    prop="giveBudgetMemo"
                    :labelCol="{ span: 3 }"
                    :wrapperCol="{ span: 21 }"
                  >
                    <a-textarea
                      v-model="projectChangeData.giveBudgetMemo"
                      auto-size
                      style="margin-top: 5px"
                      readOnly
                      :disabled="projectChangeData.status != '1'"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </section>
            <section>
              <div class="section-header">影响模块</div>
              <div class="influence-module">
                <div class="btn-box">
                  <a-button type="primary" style="width: 80px; margin-right: 15px" @click="addInfluence" v-if="btnShow"
                    >新增</a-button
                  >
                  <a-button style="width: 80px; margin-right: 15px" @click="delInfluenceData" v-if="btnShow"
                    >删除</a-button
                  >
                  <span style="color: red">
                    项目变更所影响的部门、人员填写此处，人员需添加【相关部门主管】节点步骤参与会审
                  </span>
                </div>
                <a-table
                  :columns="influenceList"
                  :data-source="influenceData"
                  bordered
                  rowKey="rowIndex"
                  :pagination="false"
                  style="margin-top: 5px"
                  :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                >
                  <template slot="deptName" slot-scope="text, record, index">
                    <a-input-search
                      class="tableInputSearch"
                      placeholder="输入部门全称"
                      v-model="record.deptName"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                      @search="openDeptSelector('influenceData', index)"
                    >
                      <a-button slot="enterButton"> ... </a-button>
                    </a-input-search>
                  </template>
                  <template slot="userName" slot-scope="text, record, index">
                    <div>
                      <UserInputSelector
                        class="tableInputSearch"
                        :username.sync="influenceData[index].userId"
                        :realname.sync="influenceData[index].userName"
                       :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                        multiple="multiple"
                        placeholder="请选择人员"
                        selectedReturn="1"
                        @selected="value=>selectInfluenceUser(value,index)"
                      />
                    </div>
                  </template>
                  <template slot="sendingFlag" slot-scope="text, record">
                    <a-select
                      style="width: 100%"
                      v-model="record.isSendTask"
                     :disabled="[2,3].indexOf(projectChangeData.status)>-1"
                    >
                      <a-select-option value="true"> 是 </a-select-option>
                      <a-select-option value="false"> 否 </a-select-option>
                    </a-select>
                  </template>
                </a-table>
              </div>
            </section>
            <section>
              <div class="section-header">附件列表</div>
              <AttachList
                ref="AttachList"
                :busField="changeId + ''"
                busType="projectChange"
                :busKey="projectBuildId"
                :zipFileName="
                  projectChangeData.projectChangeNo +
                  '#' +
                  projectBuildData.projectName +
                  '#' +
                  projectChangeData.projectChangeName
                "
                :showUpload="
                  projectChangeData.id > 0 && (['1', '2'].indexOf(projectChangeData.status) > -1 || attachEdit)
                "
                :showDelete="attachEdit || ['1', '2'].indexOf(projectChangeData.status) > -1"
                tips="需要先保存变更单后，才能对变更单上传附件。"
              />
            </section>
            <section v-if="valueTestChangeLog.length > 0">
              <div class="section-header">价值表核心力变更内容</div>
              <ValueTestChangeLog
                :valueTestChangeLog="valueTestChangeLog"
                :originLevelData="originLevelData"
                :changeLevelData="changeLevelData"
              />
            </section>
            <section v-if="processInstanceId">
              <div class="section-header">审批意见</div>
              <div class="process-engine" style="width: 100%">
                <ht-approval
                  ref="childrenRef"
                  :process-instance-id="processInstanceId"
                  :options="options"
                  :custom="custom"
                  :before-submit="beforeSubmit"
                  :before-reject="beforeReject"
                  :show-task-history="true"
                  :history-dialog="historyDialog"
                  :task-load="taskLoad"
                  :message-id="messageId"
                  :show-upload-btn="false"
                  :hidden-task-def-key="hiddenTaskDefKey"
                  :print="print"
                  :snapshotConfigs="snapshotConfigs"
                >
                </ht-approval>
              </div>
            </section>
          </a-form-model>
        </div>
      </div>
    </a-spin>
    <!--选择费用支出公司模态框-->
    <a-modal title="选择费用支出公司" :visible="showAddFactory" @ok="doAddFactory" @cancel="cancelAddFactory">
      <ul class="info-list">
        <li style="margin-bottom: 20px">
          <img src="@/assets/dbcircle.png" alt="" />
          <span class="list-title">选择费用支出公司：</span>
          <a-input-search
            placeholder="费用支出公司"
            readOnly
            v-model:value="selectFactoryData.name"
            @click="openFactorySelector()"
            style="width: 250px"
          />
        </li>
        <li style="margin-bottom: 20px">
          <img src="@/assets/dbcircle.png" alt="" />
          <span class="list-title">选择成本中心号：</span>
          <a-input
            style="width: 250px"
            placeholder="请选择成本中心号"
            v-model="addCostCenterNo"
            readOnly
            @click="selectCostCenter"
          />
        </li>
      </ul>
    </a-modal>
    <a-modal title="修改成本中心号" :visible="showChangeCenter" @ok="doChangeCenter" @cancel="showChangeCenter = false">
      <ul class="info-list">
        <li style="margin-bottom: 20px">
          <img src="@/assets/dbcircle.png" alt="" />
          <span class="list-title">原成本中心号：</span>
          <span>{{
            selectedBudgetItemRows.length
              ? selectedBudgetItemRows[0].originCostCenterNo
                ? selectedBudgetItemRows[0].originCostCenterNo
                : selectedBudgetItemRows[0].costCenterNo
              : ''
          }}</span>
        </li>
        <li style="margin-bottom: 20px">
          <img src="@/assets/dbcircle.png" alt="" />
          <span class="list-title">选择成本中心号：</span>
          <a-input
            style="width: 250px"
            placeholder="请选择成本中心号"
            v-model="addCostCenterNo"
            readOnly
            @click="selectCostCenter"
          />
        </li>
      </ul>
    </a-modal>
    <projectSelector @close="closeProjectSelector" ref="projectSelector" />
    <ChangeRecordLog ref="ChangeRecordLog" />
    <ChangeRecordHistory ref="ChangeRecordHistory" />
    <WorkReportProjectSelector @close="closeWorkReportProjectSelector" ref="WorkReportProjectSelector" />
    <ProcessUserSelect @selectUserConfirm="selectUserConfirm" ref="ProcessUserSelect" />
    <DeptSelector :show="showDeptSelector" @selected="selectDept" />
    <FactorySelector @close="selectFactorySelector" ref="FactorySelector" />
    <ChangeRecordTips ref="ChangeRecordTips" />
    <!--成本中心号选择-->
    <table-select-modal
      ref="costCenterSelect"
      :title="costCenterData.title"
      :searchPlaceholder="costCenterData.searchPlaceholder"
      :importColumns="costCenterData.columns"
      :params="costCenterData.params"
      :keywordKey="costCenterData.keywordKey"
      :isAllSelect="false"
      :listUrl="costCenterData.url"
      @ok="costCenterHandleOk"
    />
    <ChangeRecordPrint ref="showPrint"/>
  </div>
</template>
<script>
import Vue from 'vue'
import { USER_NAME, ACCESS_TOKEN } from '@/store/mutation-types'
import { Modal } from 'ant-design-vue'
import { getAction, postAction, getActionAsync, previewAttach } from '@/api/manage'
import { getQuery, formatFileSize, endWith } from '@/utils/common.js'
import '@/config/upload.install.js'
import { CodesMixin } from '@/mixins/CodesMixin'
import { UtilsMixin } from '@/mixins/UtilsMixin'
import { FlowMixin } from '@/mixins/FlowMixin'
export default {
  mixins: [CodesMixin, UtilsMixin, FlowMixin],
  components: {
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
    ProcessUserSelect: () => import('@/components/tools/ProcessUserSelect'),
    ChangeHistoryList: () => import('@/components/tools/projectBuild/ChangeHistoryList'),
    ProjectBuildChangePrint: () => import('@/views/projectBuild/projectPrint/ProjectBuildChangePrint'),
    projectSelector: () => import('@/views/projectBuild/projectSelector'),
    ChangeRecordPrint: () => import('@/views/projectChange/ChangeRecordPrint'),
    ChangeRecordLog: () => import('@/views/projectChange/ChangeRecordLog'),
    ChangeRecordHistory: () => import('@/views/projectChange/ChangeRecordHistory'),
    WorkReportProjectSelector: () => import('@/views/workReport/project/ProjectSelector'),
    ValueTestChangeLog: () => import('@/views/projectChange/ValueTestChangeLog'),
    AttachList: () => import('@/components/attach/AttachList'),
    DeptSelector: () => import('@/views/workReport/role/DeptSelector'),
    FactorySelector: () => import('@/views/projectChange/FactorySelector'),
    ChangeRecordTips: () => import('@/views/projectChange/ChangeRecordTips'),
    ExpandedRowsTable: () => import('@/views/projectBuild/budgetManage/orderInfo/expandedRowsTable'),
    TableSelectModal: () => import('@/components/tools/TableSelectModal'),
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'changeRecord',
      },
      addByProject: getQuery('addByProject', this),
      showDeptSelector: false,
      submitBtnShow: false,
      changeLogShow: false,
      btnLoading: false,
      showHistoryList: false,
      changeId: '',
      projectBuildId: '',
      processInstanceId: '',
      options: {
        request: {
          baseUrl: this.API_BASE_URL, // 业务系统根路径
          timeOut: 5000, // 请求超时时间
          interceptors: (config) => {
            config.headers['X-Access-Token'] = Vue.ls.get(ACCESS_TOKEN)
            return config
          },
        },
        userId: Vue.ls.get(USER_NAME),
      },
      currentNodeDefKey: '',
      custom: {},
      historyDialog: {
        // 审批历史模态框属性
      },
      messageId: '', // 工作台URL里面的msgId参数
      hiddenTaskDefKey: 'submit',
      currentUserId: Vue.ls.get(USER_NAME),
      url: {
        checkChangeCycleRules: '/projectBuildTime/checkProjectChangeCycleRules',
        queryBuildById: '/projectBuild/getNormalVo',
        getProjectBuildTabShowStatus: '/projectBuild/getProjectBuildTabShowStatus',
        queryOriginListByBuildId: '/projectBuildBudget/queryVoListByBuildId',
        queryChangeByBuildId: '/projectChange/queryByBuildId',
        queryChangeById: '/projectChange/queryById',
        queryChangeBudgetItemById: '/projectChange/queryChangeBudgetItemTree',
        queryChangeInfluenceData: '/projectChange/queryChangeInfluenceData',
        queryChangeLog: '/projectChange/queryChangeLogByProjectId',
        queryChangeLevelInfo: '/projectChange/queryChangeLevelInfo',
        getCodeInfoList: '/manage/codeInfo/queryByType',
        saveChange: '/projectChange/save',
        delChange: '/projectChange/delete',
        submitChange: '/projectChange/submit',
        saveCostAuditRemark: '/projectChange/saveCostAuditRemark',
        auditPass: '/projectChange/auditPass',
        auditNotPass: '/projectChange/auditNotPass',
        auditBack: '/projectChange/auditBack',
        auditCancel: '/projectChange/auditCancel',
        calcChangeRecordFlow: '/projectChange/calcChangeRecordFlow',
        startProcessFlow: '/projectChange/startProcessFlow',
        getProcessComment: '/workReport/payment/getProcessComment',
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      other: '',
      projectBuildData: {
        projectManagers: [],
        assistantProjectManagers: [],
        projectMembers: [],
      },
      projectChangeData: {
        id: 0,
        projectChangeNo: '',
        dutyDeptName: '',
        dutyUserName: '',
        changeReason: '',
        changeType: '',
        changeInfluence: '',
        changeTotal: '',
        addToSapTotal: '',
        changeContent: '',
        auditUserIds: [],
        copyForUserIds: [],
        projectBuildId: '',
        costAuditRemark: '',
      },
      budgetChangeContentList: [],
      changeContentList: [],
      contractChangeContentArr: [],
      contractCostChangeReasonArr: [],
      contractTimeChangeReasonArr: [],
      originLevelData: {},
      changeLevelData: {},
      rules: {
        dutyDeptName: [{ required: true, message: '请输入或选择主要责任部门', trigger: 'blur' }],
        dutyUserName: [{ required: true, message: '请选择主要负责人', trigger: 'blur' }],
        changeReason: [{ required: true, message: '请输入变更原因', trigger: 'blur' }],
        changeType: [{ required: true, message: '请选择变更类型', trigger: 'blur' }],
        changeInfluence: [{ required: true, message: '请输入变更后对项目的影响', trigger: 'blur' }],
        changeTotal: [{ required: true, message: '请输入变更费用', trigger: 'blur' }],
        addToSapTotal: [{ required: true, message: '请输入追加至SAP系统费用', trigger: 'blur' }],
        projectChangeName: [{ required: true, message: '请输入项目变更名称', trigger: 'blur' }],
        // budgetChangeContentList: [{ required: true, message: '请选择预算变更内容', trigger: 'change' }],
        // changeContentList: [{ required: true, message: '请选择其他变更内容', trigger: 'change' }],
        contractNumber: [{ required: true, message: '请选择变更合同编号', trigger: 'blur' }],
        contractCostChangeType: [{ required: true, message: '请选择选择费用变更类型', trigger: 'blur' }],
        contractChangeAmount: [{ required: true, message: '请输入合同变更金额', trigger: 'blur' }],
        contractCostChangeReason: [{ required: true, message: '请选择费用变更原因', trigger: 'blur' }],
        contractTimeChangeType: [{ required: true, message: '请选择进度变更类型', trigger: 'blur' }],
        contractTimeChangeDays: [{ required: true, message: '请输入进度变更影响天数', trigger: 'blur' }],
        contractTimeChangeReason: [{ required: true, message: '请选择进度变更原因', trigger: 'blur' }],
        budgetStatus: [{ required: true, message: '请输入下达状态', trigger: 'blur' }],
        wbsMemo: [{ required: true, message: '请输入调整WBS备注', trigger: 'blur' }],
        giveBudgetMemo: [{ required: true, message: '请输入下达预算备注', trigger: 'blur' }],
        projectNo: [{ required: true, message: '请填写项目编号', trigger: 'blur' }],
        projectName: [{ required: true, message: '请填写项目项目名称', trigger: 'blur' }],
        // projectManager: [{ required: true, message: '请填写项目项目经理', trigger: 'blur' }],
        costAuditRemark: [{ required: true, message: '请填写造价员审核结论', trigger: 'blur' }],
        auditChangeTotal: [{ required: true, message: '请填写审核费用', trigger: 'blur' }],
        auditAddToSapTotal: [{ required: true, message: '请填写追加至SAP金额', trigger: 'blur' }],
      },
      influenceList: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 80,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '部门',
          width: '50%',
          align: 'center',
          dataIndex: 'deptName',
          key: 'deptName',
          scopedSlots: { customRender: 'deptName' },
        },
        {
          title: '人员',
          align: 'center',
          dataIndex: 'userName',
          key: 'userName',
          scopedSlots: { customRender: 'userName' },
        },
      ],
      originTargetKeys: [],
      budgetGroupColumns: [
        {
          title: '费用支出公司',
          width: '485px',
          align: 'center',
          dataIndex: 'factoryName',
          key: 'factoryName',
          scopedSlots: { customRender: 'factoryName' },
        },
        {
          title: '代码',
          width: '150px',
          align: 'center',
          dataIndex: 'factory',
          key: 'factory',
          scopedSlots: { customRender: 'factory' },
        },
        {
          title: '成本中心号',
          width: '485px',
          align: 'center',
          dataIndex: 'costCenterNo',
          key: 'costCenterNo',
          scopedSlots: { customRender: 'costCenterNo' },
        },
      ],
      budgetListColumns: [
        { title: '分项名称', width: '150px', align: 'center', dataIndex: 'budgetItem', key: 'budgetItem' },
        { title: 'WBS号', width: '120px', align: 'center', dataIndex: 'wbsConcat', key: 'wbsConcat' },
        {
          title: '原预算金额',
          width: '120px',
          align: 'center',
          dataIndex: 'originAmount',
          key: 'originAmount',
          scopedSlots: { customRender: 'originAmount' },
        },
        {
          title: '本次变更费用',
          width: '150px',
          align: 'right',
          dataIndex: 'changeAmount',
          key: 'changeAmount',
          scopedSlots: { customRender: 'changeAmount' },
        },
        {
          title: '历史变更汇总',
          width: '150px',
          align: 'right',
          dataIndex: 'historyChangeAmount',
          key: 'historyChangeAmount',
          scopedSlots: { customRender: 'historyChangeAmount' },
        },
        {
          title: '变更说明',
          width: '479px',
          align: 'center',
          dataIndex: 'memo',
          key: 'memo',
          scopedSlots: { customRender: 'memo' },
        },
      ],
      changeCols: [
        { title: '层级', dataIndex: 'wbsLevel', key: 'wbsLevel', align: 'center', width: '120px' },
        { title: 'WBS号', dataIndex: 'wbsConcat', key: 'wbsConcat', width: '150px' },
        {
          title: 'WBS名称',
          dataIndex: 'wbsName',
          key: 'wbsName',
          width: 200,
          scopedSlots: { customRender: 'wbsName' },
        },
        {
          title: '不含税金额(元)',
          dataIndex: 'originAmount',
          key: 'originAmount',
          width: 120,
          align: 'right',
          scopedSlots: { customRender: 'originAmount' },
        },
        { title: '费用类型', dataIndex: 'budgetItem', key: 'budgetItem', width: 120, align: 'center' },
        {
          title: '本次调整预算(元)',
          dataIndex: 'changeAmount',
          key: 'changeAmount',
          width: 130,
          align: 'right',
          scopedSlots: { customRender: 'changeAmount' },
        },
        {
          title: '预算变更说明',
          dataIndex: 'memo',
          key: 'memo',
          width: 200,
          align: 'center',
          scopedSlots: { customRender: 'changeMemo' },
        },
        {
          title: '历史变更总额',
          dataIndex: 'historyChangeAmount',
          key: 'historyChangeAmount',
          width: 100,
          align: 'right',
          scopedSlots: { customRender: 'historyChangeAmount' },
        },
        {
          title: '公司代码(编码)',
          dataIndex: 'factoryCode',
          key: 'factoryCode',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'factoryCode' },
        },
        { title: '成本中心号', dataIndex: 'costCenterNo', key: 'costCenterNo', width: 100, align: 'center' },
        {
          title: '原成本中心号',
          dataIndex: 'originCostCenterNo',
          key: 'originCostCenterNo',
          width: 100,
          align: 'center',
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'changeStatus' },
        },
      ],
      rowKey: 'wbsConcat',
      tabLoading: false,
      budgetItemTree: [],
      fileList: [
        {
          title: '附件名称',
          width: '25%',
          align: 'center',
          dataIndex: 'fileName',
          key: 'fileName',
          scopedSlots: { customRender: 'fileName' },
        },
        { title: '附件大小', width: '25%', align: 'center', dataIndex: 'size', key: 'size' },
        { title: '上传时间', width: '25%', align: 'center', dataIndex: 'uploadTime', key: 'uploadTime' },
        { title: '上传者', width: '25%', align: 'center', dataIndex: 'uploaderName', key: 'uploaderName' },
      ],
      attachmentData: [],
      attachmentDataList: [],
      selectedAttachRowKeys: [],
      selectedAttachRows: [],
      attach: {
        downLoadBatch: '/common/downLoadBatch',
        deleteBatch: '/common/deleteBatch',
      },
      changeTypeData: [],
      changeTypeOptions: [],
      influenceData: [],
      baseInfoChangeLog: [],
      valueTestChangeLog: [],
      timeChangeLog: [],
      teamChangeLog: [],
      attachChangeLog: [],
      selectedRowKeys: [],
      selectedRow: [],
      selectedBudgetItemRowKeys: [],
      selectedBudgetItemRows: [],
      selectUserType: '',
      limit: 1,
      currentRecord: null,
      selUserCols: [],
      engineeringUserCols: [
        { label: '专业负责人', field: 'disciplineLeaderUser', username: '', realname: '', required: true },
        {
          label: '相关专业负责人及部门主管',
          field: 'disciplineLeaderSupervisorUser',
          username: '',
          realname: '',
          required: true,
        },
        { label: '造价部门专员', field: 'costDepartmentUser', username: '', realname: '', required: false },
        { label: '造价部门主管', field: 'costDepartmentSupervisorUser', username: '', realname: '', required: false },
        { label: '项目经理A', field: 'projectManagerUser', username: '', realname: '', required: true },
      ],
      civilEngineeringUserCols: [
        { label: '专业负责人', field: 'disciplineLeaderUser', username: '', realname: '', required: true },
        {
          label: '相关专业负责人及部门主管',
          field: 'disciplineLeaderSupervisorUser',
          username: '',
          realname: '',
          required: true,
        },
        { label: '造价部门专员', field: 'costDepartmentUser', username: '', realname: '', required: true },
        { label: '造价部门主管', field: 'costDepartmentSupervisorUser', username: '', realname: '', required: true },
        { label: '项目经理A', field: 'projectManagerUser', username: '', realname: '', required: true },
      ],
      otherUserCols: [
        { label: '部门主管', field: 'departmentManagerUser', username: '', realname: '', required: true },
      ],
      company64UserCols: [
        { label: '经营体负责人', field: 'businessManagerUser', username: '', realname: '', required: true },
        {
          label: '会审',
          field: 'jointHearingUser',
          username: 'guanjh,liaoch,lij5',
          realname: '管江华,廖长辉,李军A',
          required: true,
        },
        { label: '董秘办审批', field: 'secretaryOfficeUser', username: 'zhangx', realname: '张欣', required: true },
        { label: '集团审批', field: 'groupAuditUser', username: 'zhangr', realname: '张蓉', required: true },
      ],
      changeBudgetItemData: [],
      budgetGroups: [],
      selectBudgetItem: {
        visible: false,
        selectedRowKeys: [],
        selectedRows: [],
      },
      showAddFactory: false,
      showChangeCenter: false,
      factoryOptions: [],
      factoryData: [],
      selectFactoryData: {},
      addCostCenterNo: '',
      budgetItemData: [],
      totalAmount: '',
      totalTenThousand: '',
      totalAmountChange: '',
      totalTenThousandChange: '',
      amountHistory: '',
      amountHistoryTenThousand: '',
      snapshotConfigs: [
        {
          type: 'ref',
          value: 'imageWrapper',
        },
      ],
      activeKey: ['1'],
      printModalShowFlag: false,
      printKey: 1,
      deptSelectType: '',
      deptSelectIndex: 0,
      buildComments: [],
      selectBudgetChangeContent: false,
      showChangeContentChangeTimeOut: null,
      changeLogs: {},
      costCenterData: {
        title: '选择成本中心号',
        searchPlaceholder: '请输入关键词进行模糊搜索',
        visible: false,
        url: '/costCenter/list',
        params: { companyCode: '', costCenterName: '' },
        keywordKey: 'costCenterName',
        columns: [
          {
            title: '成本中心号',
            dataIndex: 'costCenter',
            align: 'center',
          },
          {
            title: '成本中心名称',
            dataIndex: 'costCenterName',
            align: 'center',
          },
        ],
      },
    }
  },
  computed: {
    changePercent() {
      let amountHistory = this.amountHistory
      let totalAmountChange = this.totalAmountChange
      let totalAmount = this.totalAmount
      if (amountHistory) {
        amountHistory = amountHistory.replace(new RegExp(',', 'gm'), '')
      } else {
        amountHistory = 0
      }
      if (totalAmountChange) {
        totalAmountChange = totalAmountChange.replace(new RegExp(',', 'gm'), '')
      } else {
        amountHistory = 0
      }
      if (totalAmount || totalAmount == '0') {
        totalAmount = totalAmount.replace(new RegExp(',', 'gm'), '')
      } else {
        return 0
      }
      if (totalAmount == '0') {
        return 0
      }
      return (((parseFloat(amountHistory) + parseFloat(totalAmountChange)) / parseFloat(totalAmount)) * 100).toFixed(3)
    },
    isUpper() {
      if (this.changePercent > 20) {
        return '1'
      }
      return '0'
    },
    btnShow() {
      if (
        [2, 3].indexOf(this.projectBuildData.status) <= -1 &&
        ((this.projectBuildData.projectManagers &&
          this.projectBuildData.projectManagers.indexOf(this.currentUserId) >= 0) ||
          (this.projectBuildData.assistantProjectManagers &&
            this.projectBuildData.assistantProjectManagers.indexOf(this.currentUserId) >= 0) ||
          (this.projectBuildData.projectMembers &&
            this.projectBuildData.projectMembers.indexOf(this.currentUserId) >= 0) ||
          this.projectBuildData.submitUserId == this.currentUserId ||
          this.projectBuildData.projectSubTypeAdmin)
      ) {
        return true
      } else {
        return false
      }
    },
    attachEdit() {
      if (
        (this.projectBuildData.projectManagers &&
          this.projectBuildData.projectManagers.indexOf(this.currentUserId) >= 0) ||
        (this.projectBuildData.assistantProjectManagers &&
          this.projectBuildData.assistantProjectManagers.indexOf(this.currentUserId) >= 0) ||
        (this.projectChangeData.auditUserIds != null &&
          this.projectChangeData.auditUserIds.indexOf(this.currentUserId) >= 0) ||
        (this.projectChangeData.copyForUserIds != null &&
          this.projectChangeData.copyForUserIds.indexOf(this.currentUserId) >= 0) ||
        (this.projectBuildData.projectMembers &&
          this.projectBuildData.projectMembers.indexOf(this.currentUserId) >= 0) ||
        this.projectBuildData.submitUserId == this.currentUserId ||
        this.projectBuildData.projectSubTypeAdmin
      ) {
        return true
      } else {
        return false
      }
    },
    downloadAndView() {
      return !!(
        this.attachEdit ||
        this.projectBuildData.downAndView ||
        this.projectChangeData.createUserId == this.currentUserId
      )
    },
    reserveBtnShow() {
      return (
        this.projectBuildData &&
        Object.keys(this.projectBuildData).length > 0 &&
        ((this.projectBuildData.projectManagers &&
          this.projectBuildData.projectManagers.indexOf(this.currentUserId) >= 0) ||
          (this.projectBuildData.assistantProjectManagers &&
            this.projectBuildData.assistantProjectManagers.indexOf(this.currentUserId) >= 0) ||
          this.projectBuildData.projectSubTypeAdmin) &&
        this.projectBuildData.status >= 4 &&
        this.projectBuildData.status !== 6 &&
        this.projectBuildData.status !== 7
      )
    },
    listenChange() {
      const { projectBuildId, changeId } = this
      return { projectBuildId, changeId }
    },
    buildCompanyLeader() {
      if (this.buildComments) {
        for (let comment of this.buildComments) {
          if (comment.defId == 'companyLeader') {
            return true
          }
        }
      }
      return false
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedBudgetItemRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.onSelectBudgetItemChange(selectedRowKeys, selectedRows)
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.wbsLevel < 2,
            name: record.name,
          },
        }),
      }
    },
  },
  async mounted() {
    let types = []
    types.push('工程项目变更状态')
    types.push('工程项目变更类型')
    types.push('工程项目项目预算变更类型')
    types.push('工程项目其他变更内容')
    types.push('工程项目变更合同费用变更类型')
    types.push('工程项目变更合同费用变更原因')
    types.push('工程项目变更合同进度变更类型')
    types.push('工程项目变更合同进度变更原因')
    types.push('工程项目变更合同涉及内容')
    types.push('工程项目是否海芯立项项目')
    types.push('工程项目变更操作指引')
    
    await this.fetchCodes(types)
    this.getChangeTypeData()
    this.$nextTick(() => {
      this.changeId = getQuery('changeId', this)
      this.projectBuildId = getQuery('projectBuildId', this)
    })
  },
  watch: {
    attachmentData: function (newQuestion, oldQuestion) {
      this.attachDataListFresh()
    },
    changeId: function (newV, oldV) {
      this.$emit('freshChangeId', newV)
      if (newV) {
        this.getProjectChangeData()
      }
    },
    projectBuildId: function (newV, oldV) {
      if (newV) {
        this.getProjectBuildData()
      }
    },
    listenChange: function (newV, oldV) {
      if (newV.projectBuildId && newV.changeId) {
        this.$nextTick(() => {
          this.initAttachs()
        })
      }
    },
    changeContentList: {
      handler(newV, oldV) {
        this.$emit('routerCallBack', newV)
      },
    },
    projectBuildData: {
      handler(newV, oldV) {
        this.$emit('freshProjectBuildData', newV)
        if (newV) {
          this.$set(this.projectChangeData, 'projectBuildId', newV.id)
          this.$set(this.projectChangeData, 'projectNo', newV.projectNo)
          this.$set(this.projectChangeData, 'projectName', newV.projectName)
          this.$set(this.projectChangeData, 'projectManager', newV.projectManagerName)
          this.$set(
            this.projectChangeData,
            'projectManagerId',
            newV.projectManagers ? newV.projectManagers.join(',') : ''
          )
          this.getChangeBudgetData() //获取预算变更详情
          this.getProjectBuildTabShowStatus()
          this.getBudgetItemData()
        }
        if (this.projectBuildData.processInstanceId) {
          this.fetchBuildProcessComment(this.projectBuildData.processInstanceId)
        }
      },
      deep: true,
    },
    projectChangeData: {
      handler(newV, oldV) {
        if (newV) {
        }
      },
      deep: true,
    },
    contractTimeChangeReasonArr: {
      handler(newV, oldV) {
        if (newV) {
          this.projectChangeData.contractTimeChangeReason = this.contractTimeChangeReasonArr.join(',')
        } else {
          this.projectChangeData.contractTimeChangeReason = ''
        }
      },
    },
    contractCostChangeReasonArr: {
      handler(newV, oldV) {
        if (newV) {
          this.projectChangeData.contractCostChangeReason = this.contractCostChangeReasonArr.join(',')
        } else {
          this.projectChangeData.contractCostChangeReason = ''
        }
      },
    },
    contractChangeContentArr: {
      handler(newV, oldV) {
        if (newV) {
          this.projectChangeData.contractChangeContent = this.contractChangeContentArr.join(',')
        } else {
          this.projectChangeData.contractChangeContent = ''
        }
      },
    },
  },
  methods: {
    async getProjectBuildData() {
      if (!this.projectBuildId) {
        return
      }
      let res = await getAction(this.url.queryBuildById, { id: this.projectBuildId })
      this.projectBuildData = res.result || {}
    },
    async getProjectChangeData() {
      let res = await getAction(this.url.queryChangeById, { id: this.changeId })
      if (res.success) {
        if (res.result) {
          this.projectChangeData = res.result
          if (!this.projectChangeData.costAuditRemark) {
            this.$set(this.projectChangeData, 'costAuditRemark', '')
          }
          if(this.projectChangeData.changeContent){
            this.changeContentList = this.projectChangeData.changeContent.split(",")
          }
          
          this.initProjectChangeData()
          this.getChangeInfluenceData()
          this.getChangeLogData()
        } else {
          return
        }
      }
    },
    initProjectChangeData() {
      let data = this.projectChangeData
      this.projectBuildId = data.projectBuildId
      this.processInstanceId = data.processInstanceId
      this.budgetChangeContentList = data.budgetChangeContent ? data.budgetChangeContent.split(',') : []
      this.changeContentList = data.changeContent ? data.changeContent.split(',') : []

      this.contractTimeChangeReasonArr = data.contractTimeChangeReason ? data.contractTimeChangeReason.split(',') : []
      this.contractCostChangeReasonArr = data.contractCostChangeReason ? data.contractCostChangeReason.split(',') : []
      this.contractChangeContentArr = data.contractChangeContent ? data.contractChangeContent.split(',') : []
      // if (
      //   this.projectBuildData.projectMembers &&
      //   this.projectBuildData.projectMembers.indexOf(this.currentUserId) >= 0
      // ) {
      //   if (this.changeContentList && this.changeContentList.indexOf('2') >= 0) {
      //     this.changeContentList.splice(this.changeContentList.indexOf('2'), 1)
      //   }
      //   if (this.changeContentList && this.changeContentList.indexOf('3') >= 0) {
      //     this.changeContentList.splice(this.changeContentList.indexOf('3'), 1)
      //   }
      // }
      // if (this.changeContentList && this.changeContentList.indexOf('6') >= 0) {
      //   this.changeContentList.splice(dathista.changeContentList.indexOf('6'), 1)
      // }
      if (this.budgetChangeContentList.indexOf('1') > -1) {
        this.selectBudgetChangeContent = false
      }
    },
    async getProjectBuildTabShowStatus() {
      const that = this
      if (this.projectBuildId) {
        let res = await getAction(this.url.getProjectBuildTabShowStatus, { id: this.projectBuildId })
        if (res.success) {
          if (
            !res.result.showQuest ||
            (that.projectBuildData.projectClass == '40' &&
              that.projectBuildData.projectMembers.indexOf(that.currentUserId) >= 0)
          ) {
            that.codes['工程项目其他变更内容'].forEach(function (item, index) {
              if (that.projectBuildData.status !== 4 && that.projectBuildData.status !== 5) {
                item.disabled = true
              }
              if (item.value === '2') {
                that.codes['工程项目其他变更内容'].splice(index, 1)
              }
            })
          }
          if (
            !res.result.showCoreQuest ||
            (that.projectBuildData.projectClass == '40' &&
              that.projectBuildData.projectMembers.indexOf(that.currentUserId) >= 0)
          ) {
            that.codes['工程项目其他变更内容'].forEach(function (item, index) {
              if (item.value === '3') {
                that.codes['工程项目其他变更内容'].splice(index, 1)
              }
            })
          }
        } else {
          that.$message.warning('判断价值表/上会是否显示失败:' + res.message)
        }
      }
    },
    getChangeTypeData() {
      const that = this
      getAction(this.url.getCodeInfoList, { type: '项目变更类型' }).then((res) => {
        this.changeTypeData = res.result || []
        if (this.changeTypeData.length > 0) {
          this.changeTypeData.forEach(function (item) {
            that.changeTypeOptions.push({ value: item.name.trim(), label: item.name.trim() })
          })
        }
      })
    },

    getBudgetItemData() {
      const that = this
      getAction(this.url.getCodeInfoList, { type: this.projectBuildData.projectType + '类项目预算项' }).then((res) => {
        that.budgetItemData = res.result || []
      })
    },
    getChangeInfluenceData() {
      if (this.projectChangeData.id) {
        getAction(this.url.queryChangeInfluenceData, { changeId: this.projectChangeData.id }).then((res) => {
          this.influenceData = res.result || []
        })
      }
    },
    getChangeLogData() {
      if (this.projectChangeData.projectBuildId) {
        getAction(this.url.queryChangeLog, { projectId: this.projectChangeData.projectBuildId }).then((res) => {
          let changeLogs = res.result || []
          if (changeLogs.length > 0) {
            this.changeLogShow = true
          }
          this.changeLogs = changeLogs
          let changeValueLog = []
          let changeCoreLog = []
          if (changeLogs[this.projectChangeData.projectChangeNo]) {
            this.baseInfoChangeLog = changeLogs[this.projectChangeData.projectChangeNo].filter(
              (l) => l.changeTarget === 1
            )
            this.timeChangeLog = changeLogs[this.projectChangeData.projectChangeNo].filter((l) => l.changeTarget === 3)
            this.teamChangeLog = changeLogs[this.projectChangeData.projectChangeNo].filter((l) => l.changeTarget === 4)
            changeValueLog = changeLogs[this.projectChangeData.projectChangeNo].filter((l) => l.changeTarget === 5)
            changeCoreLog = changeLogs[this.projectChangeData.projectChangeNo].filter((l) => l.changeTarget === 6)
            // this.attachChangeLog=changeLogs[this.projectChangeData.projectChangeNo].filter(l=>l.changeTarget===7);
          }

          if (this.baseInfoChangeLog.length > 0 || this.projectChangeData.status > 1) {
            this.codes['工程项目其他变更内容'].filter((l) => l.code === '0')[0].disabled = true
          }
          if (this.timeChangeLog.length > 0 || this.projectChangeData.status > 1) {
            this.codes['工程项目其他变更内容'].filter((l) => l.code === '1')[0].disabled = true
          }
          if (this.teamChangeLog.length > 0 || this.projectChangeData.status > 1) {
            this.codes['工程项目其他变更内容'].filter((l) => l.code === '5')[0].disabled = true
          }
          if (changeValueLog.length > 0 || this.projectChangeData.status > 1) {
            this.codes['工程项目其他变更内容'].filter((l) => l.code === '2')[0].disabled = true
          }
          if (changeCoreLog.length > 0 || this.projectChangeData.status > 1) {
            this.codes['工程项目其他变更内容'].filter((l) => l.code === '3')[0].disabled = true
          }
          changeValueLog = changeValueLog.concat(changeCoreLog)
          changeValueLog.sort(function (a, b) {
            return b.id - a.id
          })

          this.valueTestChangeLog = changeValueLog
          if (this.valueTestChangeLog.length > 0) {
            this.getChangeLevelInfo()
          }
        })
      }
    },
    getChangeBudgetData() {
      const that = this
      that.budgetGroups = []
      getAction(this.url.queryChangeBudgetItemById, {
        buildId: this.projectBuildId,
        changeId: this.changeId||0,
      }).then((res) => {
        /*let changeBudgetItemList = res.result || []
        if (changeBudgetItemList.length > 0) {
          let budgetGroups = that.groupBy(changeBudgetItemList, (item) => {
            return item.factoryCode
          })
          budgetGroups.forEach(function (budgetList) {
            let group = {}
            let budgetItem = budgetList[0]
            group.factoryCode = budgetItem.factoryCode
            group.factory = budgetItem.factory
            group.factoryName = budgetItem.factoryName
            group.costCenterNo = budgetItem.costCenterNo
            group.budgetList = budgetList
            that.budgetGroups.push(group)
          })
        }*/
        this.budgetItemTree = res.result || []
        this.countChangeTotal()
      })
    },
    groupBy(array, f) {
      const groups = {}
      array.forEach(function (o) {
        const group = JSON.stringify(f(o))
        groups[group] = groups[group] || []
        groups[group].push(o)
      })
      return Object.keys(groups).map(function (group) {
        return groups[group]
      })
    },
    countChangeTotal() {
      let originTotal = 0,
        changeTotal = 0,
        historyTotal = 0
      // this.budgetGroups.forEach(function (group) {
      //   group.budgetList.forEach(function (item) {
      //     originTotal += parseFloat(item.originAmount)
      //     changeTotal += parseFloat(item.changeAmount)
      //     historyTotal += parseFloat(item.historyChangeAmount)
      //   })
      // })
      this.budgetItemTree.forEach(function (item) {
        originTotal += parseFloat(item.originAmount)
        changeTotal += parseFloat(item.changeAmount)
        historyTotal += parseFloat(item.historyChangeAmount)
      })
      this.totalAmount = parseFloat(originTotal.toFixed(2)).toLocaleString()
      this.totalTenThousand = parseFloat((originTotal / 10000).toFixed(2)).toLocaleString()
      this.totalAmountChange = parseFloat(changeTotal.toFixed(2)).toLocaleString()
      this.totalTenThousandChange = parseFloat((changeTotal / 10000).toFixed(2)).toLocaleString()
      this.amountHistory = parseFloat(historyTotal.toFixed(2)).toLocaleString()
      this.amountHistoryTenThousand = parseFloat((historyTotal / 10000).toFixed(2)).toLocaleString()
    },
    getChangeLevelInfo() {
      getAction(this.url.queryChangeLevelInfo, { changeId: this.projectChangeData.id }).then((res) => {
        if (res.result) {
          this.originLevelData = res.result.originLevel
          this.changeLevelData = res.result.changeLevel
        }
      })
    },
    addInfluence() {
      let addRow = {
        id: '',
        projectChangeId: '',
        deptId: '',
        deptName: '',
        userId: '',
        userName: '',
        isSendTask: false,
      }
      this.influenceData.push(addRow)
    },

    delInfluenceData() {
      if (this.selectedRow.length === 0) {
        this.$message.warning('请先选择要删除的行')
        return
      }

      const that = this
      Modal.confirm({
        title: '提示',
        content: '确定删除选中的影响模块？',
        onOk() {
          //使用index倒序删除
          that.selectedRowKeys
            .sort((a, b) => {
              return b - a
            })
            .forEach(function (row) {
              that.influenceData.splice(row, 1)
            })
          that.selectedRow = []
          that.selectedRowKeys = []
          that.$message.success('删除成功，保存生效')
        },
        onCancel() {},
      })
    },
    addFactory() {
      if (this.budgetChangeContentList.indexOf('3') < 0) {
        this.$message.warning('请勾选预算变更内容-费用支出公司变更')
        return
      }
      this.selectFactoryData = {}
      // this.$refs.FactorySelector.openInit({ returnParam: { type: 'add' } })
      this.addCostCenterNo = ''
      this.showAddFactory = true
    },

    selectCostCenter() {
      if (this.showAddFactory) {
        if (!this.selectFactoryData.parentid) {
          this.$message.warning('请选择费用支出公司')
          return
        }
        this.costCenterData.params.companyCode = this.selectFactoryData.parentid
      }
      if (this.showChangeCenter) {
        this.costCenterData.params.companyCode = this.selectedBudgetItemRows[0].factoryCode
      }
      this.$refs.costCenterSelect.open()
    },
    costCenterHandleOk(costCenterData) {
      this.addCostCenterNo = costCenterData[0].costCenter
      this.$refs.costCenterSelect.close()
    },
    doAddFactory() {
      let vm = this
      // let checkData = this.budgetGroups.filter((b) => b.factoryCode === this.selectFactoryData)
      let checkData = []
      this.budgetItemTree.forEach((root) => {
        checkData = checkData.concat(root.children.filter((b) => b.factoryCode === vm.selectFactoryData.parentid))
      })
      if (checkData && checkData.length > 0) {
        this.$message.warning('已存在费用支出公司【' + checkData[0].factoryName + '】预算，不能重复添加')
        return
      }
      if (!this.addCostCenterNo && this.addCostCenterNo.trim() === '') {
        this.$message.warning('成本中心号必填')
        return
      }
      let factoryCode = vm.selectFactoryData.parentid.substring(0, 2)
      let costCenterNoReg = null
      eval(' costCenterNoReg= /^' + factoryCode + '\\d+((,' + factoryCode + '\\d+)*)?$/;')

      if (!costCenterNoReg.test(this.addCostCenterNo)) {
        this.$message.warning(
          '费用支出公司 [' +
          vm.selectFactoryData.name +
            '] 成本中心号必须以代码的前2位开头，只能填写数字，多个成本中心号英文逗号[,]分隔'
        )
        return
      }
      //考虑有新旧预算同时存在的情况
      let root = {
        wbsConcat: vm.projectBuildData.projectNo,
        children: [],
      }
      if (this.budgetItemTree && this.budgetItemTree.length > 0) {
        root = this.budgetItemTree.filter((b) => b.wbsConcat == vm.projectBuildData.projectNo)[0]
      }
      let second = {
        id: '',
        wbsName: vm.projectBuildData.projectName,
        wbsLevel: 2,
        wbsConcat: root.wbsConcat + '.' + vm.selectFactoryData.code.trim(),
        originAmount: 0,
        changeAmount: '0',
        historyChangeAmount: '0',
        costType: '',
        factory: vm.selectFactoryData.code.trim(),
        factoryName: vm.selectFactoryData.name.trim(),
        factoryCode: vm.selectFactoryData.parentid,
        costCenterNo: vm.addCostCenterNo,
        budgetItem: null,
        status: '新增',
        parentCode: root.wbsConcat,
        children: [],
      }
      this.budgetItemData.forEach(function (item) {
        let budget = {
          id: '',
          factory: vm.selectFactoryData.code.trim(),
          factoryName: vm.selectFactoryData.name.trim(),
          factoryCode: vm.selectFactoryData.parentid,
          costCenterNo: vm.addCostCenterNo,
          originAmount: '0',
          memo: '',
          changeAmount: '0',
          historyChangeAmount: '0',
          projectBudgetCode: item.code.trim(),
          budgetItem: item.name.trim(),
          wbsName: vm.projectBuildData.projectName + '-' + item.name.trim(),
          wbsLevel: 3,
          wbsConcat: root.wbsConcat + '.' + vm.selectFactoryData.code.trim() + '.' + item.parentid.trim(),
          costType: item.additionalField,
          status: '新增',
          parentCode: second.wbsConcat,
          children: [],
        }
        second.children.push(budget)
      })
      root.children.push(second)
      if (!this.budgetItemTree || this.budgetItemTree.length === 0) {
        this.budgetItemTree = []
        this.budgetItemTree.push(root)
      }
      this.showAddFactory = false
    },
    cancelAddFactory() {
      this.showAddFactory = false
    },
    changeCostCenter() {
      if (!this.selectedBudgetItemRows || this.selectedBudgetItemRows.length === 0) {
        this.$message.warning('请选择需要修改成本中心的数据！')
        return
      }
      let factoryCode = this.selectedBudgetItemRows[0].factoryCode
      let flag = this.selectedBudgetItemRows.some((row) => row.factoryCode !== factoryCode)
      if (flag) {
        this.$message.warning('只能选择同一公司的数据进行修改！')
        return
      }
      this.addCostCenterNo = ''
      this.showChangeCenter = true
    },
    doChangeCenter() {
      const vm = this
      if (!this.addCostCenterNo && this.addCostCenterNo.trim() === '') {
        this.$message.warning('请选择成本中心号')
        return
      }
      this.budgetItemTree.forEach((root) => {
        root.children.forEach((second) => {
          if (vm.selectedBudgetItemRowKeys.indexOf(second.wbsConcat) >= 0) {
            let originCostCenterNo = second.originCostCenterNo ? second.originCostCenterNo : second.costCenterNo
            second.costCenterNo = vm.addCostCenterNo
            if (originCostCenterNo === vm.addCostCenterNo || second.status == '新增') {
              second.originCostCenterNo = ''
            } else {
              second.originCostCenterNo = originCostCenterNo
            }
          }
          if (second.children && second.children.length > 0) {
            second.children.forEach((third) => {
              if (vm.selectedBudgetItemRowKeys.indexOf(third.wbsConcat) >= 0) {
                let originCostCenterNo = third.originCostCenterNo ? third.originCostCenterNo : third.costCenterNo
                third.costCenterNo = vm.addCostCenterNo
                if (originCostCenterNo === vm.addCostCenterNo || third.status == '新增') {
                  third.originCostCenterNo = ''
                } else {
                  third.originCostCenterNo = originCostCenterNo
                }
              }
              if (third.children && third.children.length > 0) {
                third.children.forEach((fourth) => {
                  if (vm.selectedBudgetItemRowKeys.indexOf(fourth.wbsConcat) >= 0) {
                    let originCostCenterNo = fourth.originCostCenterNo ? fourth.originCostCenterNo : fourth.costCenterNo
                    fourth.costCenterNo = vm.addCostCenterNo
                    if (originCostCenterNo === vm.addCostCenterNo || fourth.status == '新增') {
                      fourth.originCostCenterNo = ''
                    } else {
                      fourth.originCostCenterNo = originCostCenterNo
                    }
                  }
                })
              }
            })
          }
        })
      })
      this.selectedBudgetItemRows = []
      this.selectedBudgetItemRowKeys = []
      this.showChangeCenter = false
    },
    delBudgetItem() {
      if (this.budgetChangeContentList.indexOf('3') < 0) {
        this.$message.warning('请勾选预算变更内容-费用支出公司变更')
        return
      }
      if (this.selectedBudgetItemRowKeys.length === 0) {
        this.$message.warning('请先选择要删除的行')
        return
      }

      const that = this
      Modal.confirm({
        title: '提示',
        content: '确定删除选中的变更预算项？',
        onOk() {
          that.selectedBudgetItemRowKeys.forEach(function (key) {
            /*that.budgetGroups.forEach(function (item, index) {
              if (item.factoryCode === key) {
                that.budgetGroups.splice(index, 1)
              }
            })*/
            that.budgetItemTree.forEach((root) => {
              root.children.forEach((second, index) => {
                if (second.wbsConcat == key) {
                  root.children.splice(index, 1)
                }
              })
            })
          })
          that.$message.success('删除成功，保存生效')
        },
        onCancel() {},
      })
    },
    checkChangeContent(submit) {
      if (this.budgetChangeContentList.length > 0) {
        this.projectChangeData.changeTotal = !this.projectChangeData.changeTotal
          ? '0'
          : this.projectChangeData.changeTotal
        this.projectChangeData.addToSapTotal = !this.projectChangeData.addToSapTotal
          ? '0'
          : this.projectChangeData.addToSapTotal
        if (
          submit &&
          (this.projectChangeData.changeTotal.toString() === '' ||
            this.projectChangeData.addToSapTotal.toString() === '')
        ) {
          this.$message.warning('本次变更费用和追加至SAP系统费用必填')
          return false
        }
        let changeTotal = parseFloat(this.projectChangeData.changeTotal)
        if (this.projectChangeData.changeTotal.toString() !== '' && isNaN(changeTotal)) {
          this.$message.warning('请正确输入本次变更费用')
          return false
        }
        let addToSapTotal = parseFloat(this.projectChangeData.addToSapTotal)
        if (this.projectChangeData.addToSapTotal.toString() !== '' && isNaN(addToSapTotal)) {
          this.$message.warning('请正确输入加至SAP系统费用')
          return false
        }
        let changeAmountTotal = 0
        this.changeBudgetItemData = []
        /*for (let i = 0; i < this.budgetGroups.length; i++) {
          let group = this.budgetGroups[i]
          let factoryName = group.factoryName
          if (submit) {
            let factoryCode = group.factoryCode.substring(0, 2)
            let costCenterNoReg = null
            eval(' costCenterNoReg= /^' + factoryCode + '\\d+((,' + factoryCode + '\\d+)*)?$/;')

            if (!costCenterNoReg.test(group.costCenterNo)) {
              this.$message.warning(
                '费用支出公司 [' +
                  factoryName +
                  '] 成本中心号必须以代码的前2位开头，只能填写数字，多个成本中心号英文逗号[,]分隔'
              )
              return false
            }
          }
          for (let j = 0; j < group.budgetList.length; j++) {
            let item = group.budgetList[j]
            if (submit && item.changeAmount.toString() === '') {
              this.$message.warning(
                '请输入费用支出公司【' + factoryName + '】预算项【' + item.budgetItem + '】变更费用'
              )
              return false
            }
            let changeAmount = parseFloat(item.changeAmount)
            if (isNaN(changeAmount)) {
              this.$message.warning(
                '请正确输入费用支出公司【' + factoryName + '】预算项【' + item.budgetItem + '】变更费用'
              )
              return false
            }
            item.factoryName = factoryName
            item.factoryCode = group.factoryCode
            item.factory = group.factory
            item.costCenterNo = group.costCenterNo
            changeAmountTotal += changeAmount
          }
          this.changeBudgetItemData = this.changeBudgetItemData.concat(group.budgetList)
        }*/
        this.budgetItemTree.forEach((root) => {
          root.children.forEach((second) => {
            if (second.children && second.children.length > 0) {
              second.children.forEach((third) => {
                if (third.children && third.children.length > 0) {
                  third.children.forEach((item) => {
                    changeAmountTotal += parseFloat(item.changeAmount)
                  })
                } else {
                  changeAmountTotal += parseFloat(third.changeAmount)
                }
              })
            }else{
              changeAmountTotal += parseFloat(second.changeAmount)
            }
          })
        })
        if (submit && addToSapTotal.toFixed(2) !== changeAmountTotal.toFixed(2)) {
          this.$message.warning('各分项变更费用求和不等于追加SAP费用，请核对。')
          return false
        }
      }
      return true
    },
    doSubmit() {
      this.save()
      return 1
    },
    async save(autoSave) {
      this.btnLoading = true
      this.collectChangeData()

      if (!this.checkChangeContent(false)) {
        this.btnLoading = false
        return
      }
      this.projectChangeData.changeBudgetItemList =
        // this.budgetChangeContentList.length > 0 ? this.changeBudgetItemData : null
        this.budgetChangeContentList.length > 0 ? this.budgetItemTree : null
      this.projectChangeData.changeAmount =
        this.budgetChangeContentList.length > 0 ? this.projectChangeData.changeAmount : ''
      this.projectChangeData.addToSapTotal =
        this.budgetChangeContentList.length > 0 ? this.projectChangeData.addToSapTotal : ''
      let res = await postAction(this.url.saveChange, this.projectChangeData)
      this.btnLoading = false
      if (res.success) {
        this.$message.success('保存成功')
        if(!this.changeId){
          this.changeId = res.result
          this.windowOpen('/projectChange/changeRecord?changeId='+this.changeId+'&projectBuildId='+this.projectBuildId+'&pageId=8',0)
        }else{
          this.changeId = res.result
          this.$emit('freshChangeId', this.changeId)
        }
        
      } else {
        this.$message.warning('保存失败:' + res.message)
      }
      return 0
    },
    del() {
      const that = this
      Modal.confirm({
        title: '提示',
        content: '确定删除变更单？',
        onOk() {
          that.btnLoading = true
          getAction(that.url.delChange, { id: that.projectChangeData.id })
            .then((res) => {
              that.btnLoading = false
              if (res.success) {
                that.$message.success('删除成功')
                setTimeout(() => {
                  window.CloseCefTab ? window.CloseCefTab() : window.close()
                }, 1000)
              } else {
                that.$message.warning('删除失败:' + res.message)
              }
            })
            .catch((res) => {
              that.btnLoading = false
              that.$message.warning('删除失败:' + res.message)
            })
        },
        onCancel() {},
      })
    },
    onSubmit() {
      let that = this
      if (this.projectChangeData.createUserId != this.currentUserId) {
        this.$message.warning('非本人创建的变更单不能提交')
        return
      }
      if (this.changePercent > 20) {
        const h = this.$createElement
        let html = []
        html.push(h('div', '根据工程项目变更流程管理规定，如总预算调整大于立项预算20%时，应重新立项，不应继续变更。'))
        html.push(h('div', '如下继续变更请按【确定】按钮，取消变更请按【取消】按钮。'))
        Modal.confirm({
          title: '总预算调整大于立项预算提醒',
          content: h('div', {}, html),
          onOk() {
            that.toOpenProcessUserSelector()
          },
          onCancel() {
            return false
          },
        })
        return
      }
      let checkData=that.codes['工程项目其他变更内容'].filter((o) => {
        return o.additionalField=='0'&&that.changeContentList.indexOf(o.code)>=0
      });
      if(checkData&&checkData.length>0&&that.changeContentList.length>1){
        this.$message.warning('项目基本变更勾选了【'+checkData[0].name+'】,不能勾选其他内容');
        return;
      }
      this.toOpenProcessUserSelector()
    },
    toOpenProcessUserSelector() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          await this.save(false)
          if (!this.checkChangeContent(true)) {
            return
          }
          this.openProcessUserSelector()
        } else {
          this.$message.warning('提交前请按页面提醒完善相关问题')
          // document.getElementById('projectChangeNo').scrollIntoView()
          return false
        }
      })
    },
    openProcessUserSelector() {
      postAction(this.url.calcChangeRecordFlow, this.projectChangeData).then((res) => {
        if (res.success) {
          let flow = res.result
          let isUpperTips = ''
          flow.forEach((f) => {
            if (f.node == 'isUpperTips') {
              isUpperTips = f.value
            }
          })
          this.$refs.ProcessUserSelect.doSelect(flow, isUpperTips)
        }else{
          this.$message.warning('提交失败：'+e.message)
        }
      })
    },
    collectChangeData() {
      this.projectChangeData.projectBuildId = this.projectBuildId //立项ID
      this.projectChangeData.influenceList = this.influenceData //影响模块列表
      this.projectChangeData.changeContent = this.changeContentList.join(',') //其他变更内容
      this.projectChangeData.budgetChangeContent = this.budgetChangeContentList.join(',') //预算变更内容
      this.projectChangeData.changeBudgetItemList =
        // this.budgetChangeContentList.length > 0 ? this.changeBudgetItemData : null // 预算变更分项
        this.budgetChangeContentList.length > 0 ? this.budgetItemTree : null // 预算变更分项
      this.projectChangeData.changeAmount =
        this.budgetChangeContentList.length > 0 ? this.projectChangeData.changeAmount : ''
      this.projectChangeData.changePercent = this.changePercent //累计变更金额百分比
      this.projectChangeData.budgetGroups = this.budgetGroups
      this.projectChangeData.contractTimeChangeReason = this.contractTimeChangeReasonArr.join(',')
      this.projectChangeData.contractCostChangeReason = this.contractCostChangeReasonArr.join(',')
      this.projectChangeData.contractChangeContent = this.contractChangeContentArr.join(',')
    },
    checkProjectCycleRules() {
      let vm = this
      getAction(this.url.checkChangeCycleRules, { changeId: this.changeId }).then((res) => {
        if (res.code == 200) {
          if (res.result && res.result !== '') {
            let checkResult = JSON.parse(res.result)
            const h = this.$createElement
            const m = checkResult.message.split('；')
            let html = []
            html.push(h('div', '按项目周期管理要求：'))
            m.forEach((item) => {
              html.push(h('div', item))
            })
            if (checkResult.forceCanNotSubmit) {
              this.$info({
                title: '周期规则校验结果',
                content: h('div', {}, html),
                onOk() {},
              })
            } else {
              html.push(h('div', '确定提交变更单？'))
              Modal.confirm({
                title: '周期规则校验结果',
                content: h('div', {}, html),
                onOk() {
                  vm.projectChangeData.overdueProject = true
                  this.openProcessUserSelector()
                },
                onCancel() {},
              })
            }
          } else {
            vm.projectChangeData.overdueProject = false
            this.openProcessUserSelector()
          }
        } else {
          this.$message.warning('校验项目周期规则异常:' + res.message)
        }
      })
    },
    selectUserConfirm(flow) {
      if (!flow) {
        return
      }
      let data = {}
      flow.forEach((f) => {
        data[f.node] = f.value
      })
      data.buildId = this.projectBuildId
      data.changeId = this.changeId
      postAction(this.url.startProcessFlow, data).then((res) => {
        if (res.success) {
          this.$message.success('提交成功')
          this.$router.go(0)
        } else {
          this.$message.error('提交失败:' + res.message)
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRows
    },
    onSelectBudgetItemChange(selectedRowKeys, selectedRows) {
      this.selectedBudgetItemRowKeys = selectedRowKeys
      this.selectedBudgetItemRows = selectedRows
    },
    onSelectOriginItemChange(selectedRowKeys, selectedRows) {
      this.selectBudgetItem.selectedRowKeys = selectedRowKeys
      this.selectBudgetItem.selectedRows = selectedRows
    },
    checkInputMoney(event) {
      let valueStr = event.target.value
      if (valueStr !== '') {
        let value = parseFloat(valueStr)
        if (isNaN(value)) {
          this.$message.warning('请正确输入预算金额')
          return
        }
        if (value < 1000 || value > 10000000) {
          this.$info({
            title: '提示',
            content: '费用金额单位为元，填写时请注意',
            onOk() {},
          })
        }
      }
    },
    projectReserve() {
      let urlJump = this.$router.resolve({ path: '/projectBuildReserve?projectBuildId=' + this.projectBuildData.id })
      window.open(urlJump.href, '_blank')
    },
    projectChangeHistory() {
      this.showHistoryList = true
    },
    changeContentChange(checkValue) {
      //选择价值表、核心力值表，默认选择团队表
      if ((checkValue.indexOf('2') >= 0 || checkValue.indexOf('3') >= 0) && this.changeContentList.indexOf('5') < 0) {
        this.changeContentList.push('5')
      }
      this.toShowChangeContentChangeTips()
    },
    toShowChangeContentChangeTips() {
      if (this.showChangeContentChangeTimeOut) {
        window.clearTimeout(this.showChangeContentChangeTimeOut)
      }
      this.showChangeContentChangeTimeOut = window.setTimeout(this.showChangeContentChangeTips, 1500)
    },
    showChangeContentChangeTips() {
      const vm = this
      let html = []
      const h = this.$createElement
      this.changeContentList.forEach((c) => {
        if (c.parentid == '1' && c.additionalField == '1') {
          if (!vm.projectChangeData.changeContent) {
            let tabName = vm.codes['工程项目其他变更内容'].filter((o) => {
              return c == o.code
            })[0].name
            html.push(h('div', '【' + tabName + '】已勾选，请在分页界面上填写变更信息'))
          }
          if (vm.projectChangeData.changeContent && vm.projectChangeData.changeContent.indexOf(c) < 0) {
            let tabName = vm.codes['工程项目其他变更内容'].filter((o) => {
              return c == o.code
            })[0].name
            html.push(h('div', '【' + tabName + '】已勾选，请在分页界面上填写变更信息'))
          }
        }
      })

      if (html && html.length > 0) {
        Modal.confirm({
          title: '变更项目提醒',
          content: h('div', {}, html),
          onOk() {},
          onCancel() {},
        })
      }
    },
    changeContractChangeContent(checkValue) {
      if (checkValue.indexOf('91') < 0 && checkValue.indexOf('92') < 0) {
        this.$set(this.projectChangeData, 'contractNumber', '')
        this.$set(this.projectChangeData, 'contractName', '')
        this.$set(this.projectChangeData, 'contractCostNumber', '')
      }
      if (checkValue.indexOf('91') < 0) {
        this.$set(this.projectChangeData, 'contractCostChangeType', '')
        this.$set(this.projectChangeData, 'contractChangeAmount', '')
        this.$set(this.projectChangeData, 'contractCostChangeReason', '')
        this.$set(this.projectChangeData, 'contractCostChangeReasonArr', [])
      }
      if (checkValue.indexOf('92') < 0) {
        this.$set(this.projectChangeData, 'contractTimeChangeType', '')
        this.$set(this.projectChangeData, 'contractTimeChangeDays', '')
        this.$set(this.projectChangeData, 'contractTimeChangeReasonArr', [])
      }
    },
    changeAmountChange(event, record) {
      let valueStr = event.target.value
      let value = 0
      if (valueStr.toString() !== '') {
        value = parseFloat(valueStr.toString())
        if (isNaN(value)) {
          this.$message.warning('请正确输入变更费用')
        }
        record.changeAmount = value
      }
      this.countChangeAmount()
    },
    countChangeAmount() {
      let changeTotal = 0
      /*this.budgetGroups.forEach(function (group) {
        group.budgetList.forEach(function (item) {
          changeTotal += parseFloat(item.changeAmount)
        })
      })*/
      this.budgetItemTree.forEach((root) => {
        root.children.forEach((second) => {
          if (second.children && second.children.length > 0) {
            second.children.forEach((third) => {
              if (third.children && third.children.length > 0) {
                third.children.forEach((item) => {
                  changeTotal += parseFloat(item.changeAmount)
                })
              } else {
                changeTotal += parseFloat(third.changeAmount)
              }
            })
          }
        })
      })
      this.totalAmountChange = parseFloat(changeTotal.toFixed(2)).toLocaleString()
      this.totalTenThousandChange = parseFloat((changeTotal / 10000).toFixed(2)).toLocaleString()
    },
    /*===========附件方法======================*/
    attachDataListFresh() {
      this.attachmentDataList = []
      this.attachmentData.forEach((item) => {
        let size = formatFileSize(item.size)
        this.attachmentDataList.push({
          key: item.id,
          fileName: item.fileName,
          size: size,
          uploadTime: item.uploadTime,
          uploader: item.uploader,
          uploaderName: item.uploaderName,
        })
      })
    },
    showAttach(id, uploader, fileName, autoDownload) {
      if (!this.checkPermisson(uploader)) {
        this.$message.warning('仅有该附件上传人、审批人、抄送人、项目经理、副经理可以查看!')
        return
      }
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        if (autoDownload) {
          this.doDownLoadBatch(id)
          return
        }
        this.$message.warning('该附件类型不支持预览，请下载附件查看')
        return
      }
      let params = {
        id: id,
        ftpKey: 'ftp',
      }
      previewAttach(params)
        .then((result) => {
          const url = URL.createObjectURL(result)
          if (this.projectBuildData.projectClass == '40' || this.projectBuildData.projectClass == '61') {
            window.open(process.env.BASE_URL + '/pdf/web/normalViewer.html?file=' + url)
          } else {
            window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + url)
          }
        })
        .catch((err) => {
          this.$message.warning('下载文件失败')
        })
    },
    checkPermisson(uploader) {
      let currUser = Vue.ls.get(USER_NAME)
      return uploader == currUser || this.downloadAndView
    },
    onSelectAttachChange(selectedRowKeys, selectedRows) {
      this.selectedAttachRowKeys = selectedRowKeys
      this.selectedAttachRows = selectedRows
    },
    downLoadBatch() {
      if (this.selectedAttachRowKeys != null && this.selectedAttachRowKeys.length > 0) {
        this.doDownLoadBatch(this.selectedAttachRowKeys)
      } else {
        this.$message.warning('请选择要下载的其它附件')
      }
    },
    deleteBatch() {
      const that = this
      if (this.selectedAttachRowKeys != null && this.selectedAttachRowKeys.length > 0) {
        for (let row of this.selectedAttachRows) {
          if (row.uploader != this.currentUserId) {
            return this.$message.warning('请勿删除非本人上传的附件')
          }
        }
        Modal.confirm({
          title: '提示',
          content: '确定删除选中的附件？',
          onOk() {
            that.delFiles(that.selectedAttachRowKeys.join(','))
          },
          onCancel() {},
        })
      } else {
        this.$message.warning('请选择要删除的其它附件')
      }
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        let downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      let iframe = document.getElementById('_attachToolView_downloadfile_frame')
      let href =
        this.API_BASE_URL +
        this.attach.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)
      iframe.src = href
    },
    delFiles(attachIds) {
      const json = { dbKey: 'Trd', id: attachIds, ftpKey: 'ftp' }
      this.$refs.myUpload.delete(json)
    },
    /*===========流程引擎回调方法======================*/
    beforeSubmit(res) {
      // 提交前置动作
      console.log('beforeSubmit')
      const vm = this
      if (
        (this.currentNodeDefKey === 'costDepartment' || this.currentNodeDefKey === 'costDepartmentSupervisor') &&
        this.projectBuildData.projectClass === '40' &&
        this.projectChangeData.changeType === '土建'
      ) {
        if (!this.projectChangeData.auditChangeTotal || this.projectChangeData.auditChangeTotal.trim() === '') {
          this.$message.warning('请输入审核费用')
          return false
        }
        if (!this.projectChangeData.auditAddToSapTotal || this.projectChangeData.auditAddToSapTotal.trim() === '') {
          this.$message.warning('请输入追加至SAP金额')
          return false
        }
        if (!this.projectChangeData.costAuditRemark || this.projectChangeData.costAuditRemark.trim() === '') {
          // this.$message.warning('请输入造价员审核结论')
          // document.getElementById('costAuditRemark').scrollIntoView()
          // return false
        } else {
          if (this.currentNodeDefKey === 'costDepartment') {
            this.$set(this.projectChangeData, 'costAuditUser', this.userinfo.info.realname)
            this.$set(this.projectChangeData, 'costAuditUserId', this.userinfo.info.username)
          }

          postAction(this.url.saveCostAuditRemark, this.projectChangeData)
            .then((res) => {
              if (res.success) {
                vm.$refs.childrenRef.submitTaskNotBefore()
              } else {
                this.$message.warning('保存造价员审核结论失败:' + res.message)
              }
            })
            .catch((res) => {
              this.$message.warning('保存造价员审核结论失败:' + res.message)
            })
        }
        return false
      }
      return true
    },
    beforeReject(res) {
      // 驳回前置动作
      if (this.checkOptionValue()) {
        // return this.doAuditNotPass()
        return true
      } else {
        return false
      }
    },
    taskLoad(task) {
      // 当前任务加载回调函数，获取当前任务信息
      this.currentNodeDefKey = task.taskDefKey
    },
    //-------------流程回调------end
    doAuditPass() {
      let flag = false
      postAction(this.url.auditPass, {
        id: this.projectChangeData.id,
        costAuditRemark: this.projectChangeData.costAuditRemark,
      }).then((res) => {
        if (res.code == 200) {
          flag = true
        } else {
          this.$message.warning('流程审批通过接口异常:' + res.message)
        }
      })
      return flag
    },
    async doAuditNotPass() {
      let flag = false
      await getActionAsync(this.url.auditNotPass, { changeId: this.projectChangeData.id }).then((res) => {
        if (res.code == 200) {
          flag = true
          this.$router.go(0)
        } else {
          this.$message.warning('流程审批不通过接口异常:' + res.message)
        }
      })
      return flag
    },
    doAuditBack(backKey) {
      let flag = false
      getAction(this.url.auditBack, { changeId: this.projectChangeData.id, backKey: backKey }).then((res) => {
        if (res.code == 200) {
          flag = true
          this.$router.go(0)
        } else {
          this.$message.warning('流程审批退回接口异常:' + res.message)
        }
      })
      return flag
    },
    async doAuditCancel() {
      let flag = false
      await getActionAsync(this.url.auditCancel, { changeId: this.projectChangeData.id }).then((res) => {
        if (res.code == 200) {
          flag = true
        } else {
          this.$message.warning('流程审批退回接口异常:' + res.message)
        }
      })
      return flag
    },
    checkOptionValue() {
      let options = this.$refs.childrenRef.data
      if (options == '' || options == null || options == undefined) {
        this.$message.warning('请输入审批意见')
        return false
      } else {
        return true
      }
    },
    print() {
      ++this.printKey
      this.printModalShowFlag = true
    },
    getApplyUserAndDept() {
      let result = ''
      if (this.projectChangeData) {
        result = this.projectChangeData.createUserName ? this.projectChangeData.createUserName : ''
      }
      if (this.projectChangeData) {
        result += "/"+(this.projectChangeData.createDeptName ? this.projectChangeData.createDeptName : '')
      }
      return result
    },
    openProjectSelector() {
      this.$refs.projectSelector.openInit({ projectClasses: ['40', '41'] })
    },
    closeProjectSelector(project) {
      if (project) {
        this.projectBuildId = project.id
      }
    },
    openChangeRecordLog() {
      this.$refs.ChangeRecordLog.init(this.activeKey, this.projectChangeData.projectChangeNo, this.changeLogs)
    },
    openChangeRecordHistory() {
      if (!this.projectBuildId || !this.projectBuildData.projectNo || !this.projectBuildData.projectName) {
        return this.$message('请选选择项目编号')
      }
      this.$refs.ChangeRecordHistory.openInit(
        this.projectBuildId,
        this.projectBuildData.projectNo,
        this.projectBuildData.projectName,
        this.projectBuildData.projectManager
      )
    },
    openWorkReportProjectSelector() {
      if (!this.projectBuildId || !this.projectBuildData.projectNo || !this.projectBuildData.projectName) {
        return this.$message('请选选择项目编号')
      }
      this.$refs.WorkReportProjectSelector.init(this.projectBuildData.projectNo)
    },
    closeWorkReportProjectSelector(project) {
      if (project) {
        this.$set(this.projectChangeData, 'contractNumber', project.contractNumber)
        this.$set(this.projectChangeData, 'contractName', project.contractName)
        this.$set(this.projectChangeData, 'contractCostNumber', project.costNumber)
      }
    },
    openDeptSelector(type, index) {
      this.showDeptSelector = true
      this.deptSelectType = type
      this.deptSelectIndex = index
    },
    selectDept(selection) {
      if (selection && selection.length > 0) {
        if ('influenceData' == this.deptSelectType) {
          this.$set(this.influenceData[this.deptSelectIndex], 'deptName', selection[0].deptname.trim())
        } else {
          this.$set(this.projectChangeData, 'dutyDeptName', selection[0].deptname.trim())
        }
      }
      this.showDeptSelector = false
    },
    changeIsHteProject() {
      this.$set(this.projectChangeData, 'projectBuildId', '')
      this.$set(this.projectChangeData, 'projectNo', '')
      this.$set(this.projectChangeData, 'projectName', '')
      this.$set(this.projectChangeData, 'projectManager', '')
      this.$set(this.projectChangeData, 'projectManagerId', '')
    },
    changeBudgetChangeContentList(v) {
      const h = this.$createElement
      if (this.budgetChangeContentList.indexOf('1') > -1 && !this.selectBudgetChangeContent) {
        this.selectBudgetChangeContent = true
        Modal.confirm({
          title: '项目总预算调整',
          content: h('div', {}, html),
          onOk() {},
          onCancel() {},
        })
      } else {
        this.selectBudgetChangeContent = false
      }
      if (this.budgetChangeContentList.indexOf('2') > -1) {
        this.$set(this.projectChangeData, 'addToSapTotal', '')
      }
    },
    initAttachs() {
      if (!this.$refs.AttachList) {
        setTimeout(this.initAttachs, 2000)
      } else {
        this.$refs.AttachList.fetchAttach()
      }
    },
    openFactorySelector() {
      this.$refs.FactorySelector.openInit({ returnParam: { type: 'add' } })
    },
    selectFactorySelector(item, returnParam) {
      /*if (returnParam.type == 'edit') {
        let group = returnParam.group
        let checkData = this.budgetGroups.filter((group) => group.factoryCode == item.code)
        if (checkData.length > 1) {
          this.$message.warning('已存在费用支出公司【' + item.name.trim() + '】预算')
          item = this.factoryData.filter((item) => item.code.trim() === group.factory)[0]
          group.factoryCode = item.parentid
          return
        }
        group.factory = item.code.trim()
        group.factoryCode = item.parentid
        group.factoryName = item.name.trim()
        this.group.budgetList[returnParam.index] = group
      }*/
      if (returnParam.type == 'add') {
        this.selectFactoryData = item
        this.$set(this.selectFactoryData, 'name', item.name)
        // this.doAddFactory()
      }
    },
    async fetchBuildProcessComment(flowId) {
      if (!flowId) {
        return
      }
      let res = await getAction(this.url.getProcessComment + '/' + flowId, {})
      if (res.success) {
        this.buildComments = res.result
      } else {
        this.$message.error(res.message)
      }
    },
    toProjectDetail() {
      if (this.projectBuildData) {
        this.projectDetail(
          this.projectBuildData.id,
          this.projectBuildData.status,
          this.projectBuildData.projectType,
          1,
          1
        )
      }
    },
    projectDetail(id, status, projectType, projectAll, projectMember) {
      if (projectAll != 1 && projectMember != 1) {
        return
      }

      if (projectAll == 1) {
        var detailUrl =
          this.HTE_OLD_SERVER_URL +
          `/projectBuild/buildBasic?bootToken=${Vue.ls.get(ACCESS_TOKEN)}&id=${id}&projectClassCode=${
            this.activeCode
          }&projectType=${this.projectType}`
        //查看明细功能
        let projectDetailUrl =
          status === 1
            ? detailUrl
            : status === 2 || status === 3
            ? this.HTE_OLD_SERVER_URL + `/projectBuild/audit?bootToken=${Vue.ls.get(ACCESS_TOKEN)}&id=${id}`
            : this.HTE_OLD_SERVER_URL + `/projectBuild/auditDetail?bootToken=${Vue.ls.get(ACCESS_TOKEN)}&id=${id}`
        window.open(projectDetailUrl, '_blank')
        return
      }
      if (projectMember == 1) {
        let urlJump = this.$router.resolve({
          path: `/projectbuildstup/baseInfo?projectBuildId=` + id + '&projectMember=1',
        })
        window.open(urlJump.href, '_blank')
        return
      }
    },
    openChangeRecordTips() {
      this.$refs.ChangeRecordTips.open()
    },
    openChangeRecordGuide(){
      this.windowOpen('/library/file/view/4/' + this.codes["工程项目变更操作指引"][0].code + '/0')
    },
    async toPrint(){
      let map = {"totalAmount":this.totalAmount,"totalTenThousand":this.totalTenThousand,"totalAmountChange":this.totalAmountChange,"totalTenThousandChange":this.totalTenThousandChange,"amountHistory":this.amountHistory,"amountHistoryTenThousand":this.amountHistoryTenThousand,"changePercent":this.changePercent}
      if(this.projectChangeData.processInstanceId){
        await this.fetchFlowComments(this.projectChangeData.processInstanceId)
      }
      this.$refs.showPrint.open(this.projectChangeData,this.projectBuildData,this.budgetChangeContentList,this.budgetItemTree,map,this.comments)
    },
    selectInfluenceUser(users,index){
      let deptNames = []
      if(users){
        users.forEach(u=>{
          deptNames.push(u.deptName)
        })
      }
      let record = this.influenceData[index]
      record.deptName = deptNames.join(",")
      this.influenceData[index] = record
    },
    selectdutyUser(users){
      let deptNames = []
      if(users){
        users.forEach(u=>{
          deptNames.push(u.deptName)
        })
      }
      this.$set(this.projectChangeData,"dutyDeptName",deptNames.join(","))
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-table-tbody .ant-select-selection {
  border-radius: unset;
  border: unset;
}

/deep/ .ant-btn-primary {
  background: #4095e4;
}

/deep/ .ant-btn {
  border-radius: unset;
}

/deep/ .ant-table-thead > tr > th {
  background: #dadee9 !important;
}

/deep/.ant-table-small,
/deep/.ant-table-thead > tr:first-child > th:first-child,
/deep/.ant-table-thead > tr:first-child > th:last-child {
  border-radius: unset;
}

/deep/.ant-table-thead > tr > th,
/deep/.ant-table-tbody > tr > td,
/deep/.ant-table-tbody .ant-table-row td {
  padding: 10px 16px;
}

/deep/.ant-card-small > .ant-card-head {
  background: #f6f7f9;
}

/deep/.ant-collapse > .ant-collapse-item > .ant-collapse-header {
  border-radius: unset;
  padding: 8px 32px;
  background: #f6f7f9;
}

/deep/.ant-collapse > .ant-collapse-item > .ant-collapse-content {
  height: 250px;
  overflow-y: scroll;
}

/deep/.ant-timeline-item-content {
  display: flex;
  justify-content: space-between;

  > div:last-child {
    min-width: 9vw;
    text-align: right;
    color: #999;
  }
}

.process-engine {
  /deep/ #process-container {
    width: unset !important;
  }

  /deep/ #process-container .process-item .info-fullMessage {
    max-width: 1200px;
  }
}

#change-record {
  border: 1px solid #e6e6e6;
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 55px;

  h4 {
    font-weight: bolder;
    display: inline-block;
    position: relative;
    padding-left: 13px;

    &:before {
      content: '';
      position: absolute;
      display: inline-block;
      top: 5%;
      left: 0;
      background-color: #47a4fa;
      width: 3px;
      height: 90%;
    }
  }

  .container {
    // margin:30px 125px 0;
    height: inherit;

    .title {
      display: flex;
      justify-content: center;
      margin-bottom: 15px;

      h3 {
        font-size: 18px;
        font-weight: 600;
        margin-right: 25px;
      }

      .icon-plus {
        font-size: 13px;
        padding-right: 5px;
      }
    }

    .content {
      background-color: #fff;

      // border: 1px solid #eaeaea;
      .tip-head {
        padding: 11px 19px 0px;
        position: relative;
        top: 3px;
      }

      .content-title {
        border-bottom: 1px solid #f2f2f2;
        padding: 15px 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .header {
          span {
            margin-right: 30px;
          }
        }
      }

      .content-container {
        padding: 20px;

        ul {
          list-style: none;
          padding: 0;
        }

        .change-info {
          display: flex;

          li {
            margin-right: 120px;
          }
        }

        .change-explain {
          li {
            margin-bottom: 15px;
          }
        }

        .influence-module {
          h4 {
            margin: 15px 0;
          }

          .btn-box {
            margin-bottom: 10px;
            display: flex;
          }
        }

        .change-record {
          h4 {
            margin: 15px 0;
          }

          .record-container {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;

            > li {
              width: 50%;
              margin-bottom: 15px;

              &:nth-child(odd) {
                .ant-collapse {
                  margin-right: 1%;
                  width: 99%;
                }
              }

              &:nth-child(even) {
                .ant-collapse {
                  margin-left: 1%;
                  width: 99%;
                }
              }
            }
          }
        }

        .btn {
          display: flex;
          justify-content: center;
          margin-top: 30px;
          position: fixed;
          bottom: 15px;
          left: 0;
          width: 100%;
          z-index: 1;

          > button {
            min-width: 150px;
            margin: 0 5px;
          }
        }
      }

      .infoTips {
        background: #e6f7ff;
        border: 1px solid #aee1ff;
        border-radius: 4px;
        padding: 5px 10px;
        font-size: 12px;
        color: #888;
      }
    }
  }
}

.line-content {
  .ant-col-8 {
    width: 30%;

    &:first-child {
      width: 40%;
    }
  }
}

.content-container .dept {
  /deep/ .ant-form-item .ant-form-item-label {
    width: 165px;
  }
}

.info-detail {
  background-color: #f6f7f9;
  border: 1px solid #ebebeb;
  padding: 1% 2.5%;
  position: relative;
  margin-bottom: 20px;

  .info-list {
    margin: 0;
    font-size: 16px;
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 15px;

    > li {
      width: 25%;
      height: 25px;
      display: flex;
      align-items: center;

      > img {
        margin-right: 5px;
      }

      .list-title {
        height: unset;
        font-weight: 900;
      }
    }

    .one-row {
      width: 100%;
    }
  }

  .info-content {
    .content-title {
      display: flex;
      align-items: center;
      font-weight: 900;

      img {
        margin-right: 5px;
      }
    }

    .content-box {
      padding: 5px 16px 0;
    }
  }

  .redfont {
    color: #fe6e6c;
    font-weight: bold;
    font-size: 18px;

    &.borderleft::after {
      content: '';
      width: 1px;
      height: 10px;
      color: red;
      border-left: 1px solid #e3e3e3;
      position: absolute;
      left: -40px;
      top: 0;
      bottom: 0;
      margin: auto;
    }
  }
}

.info-list {
  display: flex;
  flex-wrap: wrap;
  border-bottom: 1px dashed #ebebeb;

  > li {
    width: 100%;
    height: 25px;
    display: flex;
    align-items: center;

    > img {
      margin-right: 5px;
    }

    .list-title {
      width: 150px;
      font-weight: 900;
    }
  }
}

/deep/.ant-table-placeholder {
  z-index: unset;
}

.totalExpenses {
  display: flex;
  justify-content: space-between;
  font-weight: bolder;
  margin-top: 10px;
}

/deep/ .ant-table-body::-webkit-scrollbar-track {
  background-color: #fff;
}

/deep/ .ant-checkbox-disabled + span {
  color: unset;
}

/deep/ div.inner-table.ant-table-wrapper {
  margin: -7px -11px 5px -11px;

  table {
    border: none;
  }
}

.full-modal {
  /deep/ .ant-modal {
    max-width: 100%;
    top: 0 !important;
    padding-bottom: 0;
    margin: 0;
  }

  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }

  .ant-modal-body {
    flex: 1;
  }
}

/deep/ .full-modal {
  /deep/ .ant-modal {
    top: 0 !important;
  }
}
</style>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.page-main {
  height: auto;

  .banner {
    background-image: url(../../assets/contract-top.png);
  }

  .container {
    padding: 0px 0px 0px;

    .content-list {
      margin-top: 15px;
    }
  }

  .font-active {
    cursor: pointer;
  }
}

/deep/.ant-select-dropdown {
  width: 400px !important;
}
.multipleForm /deep/.ant-form-item-control-wrapper {
  width: 100% !important;
}

/deep/.ant-table .ant-table-tbody .ant-table-row td .tableSelect input {
  padding: 0px !important;
}
/deep/.ant-table .ant-table-tbody .ant-table-row td .tableInputSearch input {
  padding: 0px !important;
  height: 32px !important;
}
.tipsLabel /deep/ .ant-form-item-label > label {
  color: #ff0000 !important;
}
</style>
